赞
踩
在实际的业务中往往需要把提交但尚未上传的图片显示回前端,等待上传,以下方法是将提交后的图片回显的方法
- <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>
- 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'
- }
- })
- });
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。