当前位置:   article > 正文

vue前端实现图片预览加token_vue前端src的路径图片需要token

vue前端src的路径图片需要token

需求:最近提了一个安全需求就是上传得图片预览时需要进行验证加token,众所周知img展示图片是不能加token的;

解决:

1:创建一个组件

  1. <template>
  2. <img ref="img" />
  3. </template>
  4. <script src="./tokenImg.ts"></script>
  5. tokenImg.ts
  6. import { Vue, Component } from 'vue';
  7. import { Prop } from 'vue-property-decorator';
  8. @Component({
  9. name: 'auth-img'
  10. })
  11. export default class AuthImgCom extends Vue {
  12. @Prop() imgUrl!: string;
  13. mounted() {
  14. Object.defineProperty(Image.prototype, 'imgUrl', {
  15. writable: true,
  16. enumerable: true,
  17. configurable: true
  18. });
  19. const img = this.$refs.img as any;
  20. const request = new XMLHttpRequest() as any;
  21. request.responseType = 'blob';
  22. request.open('get', this.imgUrl, true);
  23. // 这里带上请求头(我的项目token存在locaStorage里,其他根据自身项目情况获取token)
  24. const token = JSON.parse(localStorage.getItem('token'));
  25. request.setRequestHeader('access-token', token.token);
  26. request.onreadystatechange = e => {
  27. if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
  28. img.src = URL.createObjectURL(request.response);
  29. img.onload = () => {
  30. URL.revokeObjectURL(img.src);
  31. };
  32. }
  33. };
  34. request.send(null);
  35. }
  36. }

2:使用预览或者回显的时候

  1. // 点击放大镜预览的时候
  2. <!-- 图片预览 -->
  3. <el-dialog :visible.sync="dialogVisible" title="预览" class="scrollInnerDialog">
  4. <token-img width="100%" :imgSrc="dialogImageUrl"></token-img>
  5. </el-dialog>
  6. // 这是上传完成回显
  7. <el-upload
  8. action
  9. :file-list="fileList"
  10. :disabled="view"
  11. :loading="uploading"
  12. list-type="picture-card"
  13. :http-request="val => upload(val)"
  14. >
  15. <i slot="default" class="el-icon-plus"></i>
  16. <div slot="file" slot-scope="{ file }">
  17. <token-img class="el-upload-list__item-thumbnai :imgSrc="file.fileUrl"></token-img>
  18. <span class="el-upload-list__item-actions">
  19. <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
  20. <i class="el-icon-zoom-in"></i>
  21. </span>
  22. <span v-if="!view" class="el-upload-list__item-delete" @click="handleRemove(file, 'opinionFile')">
  23. <i class="el-icon-delete"></i>
  24. </span>
  25. </span>
  26. </div>
  27. </el-upload>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/283706
推荐阅读
相关标签
  

闽ICP备14008679号