element-ui upload组件上传图片使用上传图片展示

243 阅读1分钟
//之前是使用后端返回的url的,现在根据业务需要改为使用localFileUrl
this.localFileUrl = URL.createObjectURL(content.file);
// upload.vue
<template>
  <div>
    <el-upload class="upload-demo1" :class="customClass" drag action v-loading="loading"
               element-loading-text="拼命加载中"
               element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
               :http-request="myUpload"
               :on-preview="previewFile" :on-remove="handleRemove" :on-exceed="handleExceedVisio"
               :before-remove="beforeRemove"
               :file-list="fileList" :limit="1">
      <img v-if="value" :src="localFileUrl||value" class="avatar">
      <div v-else>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处,或
          <em>点击上传</em>
        </div>
      </div>
      <!-- <div class="el-upload__tip" slot="tip">
        可上传多个文件,单个文件大小不超过10mb
      </div> -->
    </el-upload>
  </div>
</template>
<script>


import {uploadFile} from "@/api/upload";

export default {
  name: "FileUpload",
  props: {
    customClass: String,
    // 上传文件的类型
    category: String,
    // 上传文件的链接
    value: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      valuePrefix: process.env.VUE_APP_BASE_IMAGE,
      //单个文件Id集合
      // graphUrl: '',
      localFileUrl: '',
      fileIds: [],
      fileList: [],
      loading: false,
    };
  },
  watch: {},
  created() {},
  methods: {
    previewFile(file) {
      if (file.raw.url) {
        window.open(file.raw.url, "_blank");
      }
    },
    /**
     * 自定义上传请求
     */
    myUpload(content) {
      // console.log('content.file😊===》', content.file)
      this.loading = true;
      let formData = new FormData();
      formData.append("file", content.file);
      formData.append("category", this.category);
      const params = {
        category: this.category
      }
      // console.log('自定义上传请求😊===》', formData, params)
      // return
      uploadFile(formData, params).then((res) => {
        this.loading = false;
        let data = res.data;
        this.localFileUrl = URL.createObjectURL(content.file);
        content.file.url = data;
        content.onSuccess();
        this.$emit('input', data)
      }).catch(err => {
        this.$emit('input', '')
        this.localFileUrl = ''
        this.loading = false;
        this.$message.error('上传失败')
      });
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.raw.name}?`);
    },
    //删除功能的具体展示
    handleRemove(file, fileList) {
      this.$emit('input', '')
      this.localFileUrl = ''
    },
    handleExceedVisio() {
      this.$message.warning(`当前限制选择 1 个文件,请删除后继续上传!`)
    }
  },
};
</script>

<style scoped lang="scss">
.avatar {
  width: 100%;
  height: 100%;
}
</style>
<style lang="scss">
//.upload-demo1{
//  .el-upload-dragger{
//    width: 100%;
//  }
//}
</style>

接口这里后端也改为返回blob了

// api/upload.js
/**
 * blob图片文件流
 * @param {string} url
 * @returns
 */
export async function getWebImage(url) {
    return request({
        url:`/xxxxxxxxx?url=${url}`,
        method: "get",
        responseType: 'blob',
    }).then((response) => {
        const blob = response ;
        return URL.createObjectURL(blob);
    }).catch((err) => {
        return ''
    })
}

使用页面

// xxx.vue
 
import {getWebImage} from "@/api/upload";

fetchList(this.searchForm).then(res => {
  res.data.records.map(async (it) => {
    // 检查并处理属性
    if (it.sceneThumb) {
    // 把sceneThumb改为blob格式
      it.sceneThumb = await getWebImage(it.sceneThumb);
    }
    return it;
  })
  this.tableData = res.data.records
})