Element-plus之el-upload上传图片后回显,以及将回显的图片再次上传

时间:2025-02-17 20:06:50

在实际的业务中往往需要把提交但尚未上传的图片显示回前端,等待上传,以下方法是将提交后的图片回显的方法

<template>
    <el-upload
            action="/api/imageContainer/saveOrUpdate"
            accept="image/bmp,image/jpeg,image/jpg,image/png,image/webp"
            :on-change="handleChange"
            ref="upload"
            name="file"
            :show-file-list="false"
            :limit = "1"
            :on-exceed="handleExceed"
            :auto-upload="false"
          >
            <img v-if="" :src="" />
            <el-icon v-else class="articleImage-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip" style="text-align: center;color: rgb(255, 0, 0);">
                只能上传一张小于等于10MB的图片
              </div>
            </template>
          </el-upload>
    <el-button type="primary" @click="submitUpload()">确认</el-button>
</template>

<script lang="ts" setup>
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const upload = ref<UploadInstance>()
const imageContainer  = reactive({
  imageUrl: '',
})

/** 
 * 文件回显
 */
const handleChange = (file: any, fileList: any) => {
   = (!)
}

/** 
 * 文件重覆盖
 */
const handleExceed: UploadProps['onExceed'] = (files) => {
  !.clearFiles()
  const file = files[0] as UploadRawFile
   = genFileId()
  !.handleStart(file)
}

/** 
 * 文件手动上传
 */
const submitUpload = () => {
  !.submit()
}
</script>

在实际的业务中,有时候会需要将回显后的图片再次上传,此时只需要修改上述的submitUpload()方法即可,取消el-upload的手动提交,改为自己提交请求,代码如下

具体做法是把url转换成blob类型,然后再把blob类型转换成file类型,最后添加进formdata中即可实现上传 

/**
 * 上传图片
 */
const submitUpload = () => {
  //!.submit() 不使用el-upload提供的手动上传方法
  fetch() // 把后端返回的链接转换成blob类型然后再转换成file类型
  .then(response => ())
  .then(blob => {
    const file= new File([blob], '', { type: "image/bmp,image/jpeg,image/png,image/webp" }); // 图片名我用'',因为我的后端写了方法重命名
    const formData = new FormData();
    ('file', file);
    ("/api/imageContainer/saveOrUpdate", formData, {
      headers: {
      'Content-Type': 'multipart/form-data'
    }
    })
  });
}