vue前端实现图片预览加token

需求:最近提了一个安全需求就是上传得图片预览时需要进行验证加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>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值