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

本文介绍了如何在Vue应用中使用Element-Plus的el-upload组件展示待上传图片,并在需要时切换到手动上传,通过处理URL到Blob再到File的转换,使用axios发送POST请求更新图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

<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="imageContainer.imageUrl" :src="imageContainer.imageUrl" />
            <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) => {
  imageContainer.imageUrl = URL.createObjectURL(file.raw!)
}

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

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CVPlayer-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值