vue前端实现图片预览加token
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
·
需求:最近提了一个安全需求就是上传得图片预览时需要进行验证加token,众所周知img展示图片是不能加token的;
解决:
1:创建一个组件
<template>
<img ref="img" />
</template>
<script src="./tokenImg.ts"></script>
tokenImg.ts
import { Vue, Component } from 'vue';
import { Prop } from 'vue-property-decorator';
@Component({
name: 'auth-img'
})
export default class AuthImgCom extends Vue {
@Prop() imgUrl!: string;
mounted() {
Object.defineProperty(Image.prototype, 'imgUrl', {
writable: true,
enumerable: true,
configurable: true
});
const img = this.$refs.img as any;
const request = new XMLHttpRequest() as any;
request.responseType = 'blob';
request.open('get', this.imgUrl, true);
// 这里带上请求头(我的项目token存在locaStorage里,其他根据自身项目情况获取token)
const token = JSON.parse(localStorage.getItem('token'));
request.setRequestHeader('access-token', token.token);
request.onreadystatechange = e => {
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
img.src = URL.createObjectURL(request.response);
img.onload = () => {
URL.revokeObjectURL(img.src);
};
}
};
request.send(null);
}
}
2:使用预览或者回显的时候
// 点击放大镜预览的时候
<!-- 图片预览 -->
<el-dialog :visible.sync="dialogVisible" title="预览" class="scrollInnerDialog">
<token-img width="100%" :imgSrc="dialogImageUrl"></token-img>
</el-dialog>
// 这是上传完成回显
<el-upload
action
:file-list="fileList"
:disabled="view"
:loading="uploading"
list-type="picture-card"
:http-request="val => upload(val)"
>
<i slot="default" class="el-icon-plus"></i>
<div slot="file" slot-scope="{ file }">
<token-img class="el-upload-list__item-thumbnai :imgSrc="file.fileUrl"></token-img>
<span class="el-upload-list__item-actions">
<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
<i class="el-icon-zoom-in"></i>
</span>
<span v-if="!view" class="el-upload-list__item-delete" @click="handleRemove(file, 'opinionFile')">
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
9e887079
[skip ci] 1 年前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)