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

Logo

前往低代码交流专区

更多推荐