当前位置: 首页 > news >正文

el-upload上传图片图片、el-load默认图片重新上传、el-upload初始化图片、el-upload编辑时回显图片

  • 问题
    我用el-upload上传图片,再上一篇文章已经解决了,el-upload上传图片给SpringBoot后端,但是又发现了新的问题,果然bug是一个个的冒出来的。新的问题是el-upload编辑时回显图片的保存
    • 问题描述:回显图片需要将默认的 file-list设置为data中的属性,以设置默认值。如下,设置为imgList
 <el-uploadaction=""list-type="picture-card"multiple:on-change="handlChange":file-list="imgList":on-error="handleErr"ref="upload":limit="10"accept=".jpg,.png,.jpeg":on-exceed="handleMaxNum":auto-upload="false"><i slot="default" class="el-icon-plus"></i><div slot="file" slot-scope="{file}"><imgclass="el-upload-list__item-thumbnail":src="file.url" alt=""><span class="el-upload-list__item-actions"><spanclass="el-upload-list__item-preview"@click="handlePictureCardPreview(file)"><i class="el-icon-zoom-in"></i></span><spanclass="el-upload-list__item-delete"@click="handleRemove(file)"><i class="el-icon-delete"></i></span></span></div></el-upload>

但是这样的自己设置的值,他的格式是这样的:

this.imgList = this.imgList.map(url => ({url: url,})

与自己上传文件通过:file_list得到的内容不同,(也就是如果你有个添加图片的功能,有个编辑图片的功能,编辑功能你要设置初始值,但是他们的imgList不一样),有图为证
在这里插入图片描述
在这里插入图片描述
这会导致什么呢?首先,我们需要将imgList的文件转成FormData格式的文件传给后端,通过获取file-ist,可以通过:on-change="handlChange"获取

 handleChange(file, fileList) {this.imgList = fileList;},
  1. 如果你是添加图片的功能的时候,他是没问题的,可以直接使用
    formData.append('files', item.raw);转成FormData的类型。
  2. 但是如果你是要回显图片再保存,即编辑的功能,这个时候你要设置初始值,即用上面所说的方式设置。这种格式的的imgList,就不能直接使用 formData.append('files', item.raw);这种方式转成FormData,而要使用fetch的方式
  • 解决
    下面是解决的代码,可以先对imgList的url进行判断,因为自己上传的url开头是不带"blob"的,顺便说一下,因为fetch是异步的,所以要通过设置Promise,等fetch全部执行完再进行保存图片,否则FormData还是会为空
this.imgList.forEach(item => {let url = item.url;if(url.startsWith("blob")){formData.append('files', item.raw);}else {let promise = fetch(url, {headers: new Headers({'Origin': location.origin}),mode: 'no-cors'}).then(response => response.blob()).then(blob => {// 创建 URL 对象以便提取文件名let filename = url.split('/').pop();// 创建一个虚拟的 File 对象let file = new File([blob], filename, {type: 'image/bmp,image/jpeg,image/png,image/webp'});console.log(file)formData.append('files', file);}).catch(error => {console.error('Failed to fetch image:', error);});promises.push(promise);}});Promise.all(promises).then(() => {console.log("formdata", formData)let uri = "/" + newAttractionIdsaveImgs(uri, formData).then(resPic => {if (resPic.data.success) {// this.$message({//   type:"success",//   message:resPic.data.msg// })} else {this.$message({type: "info",message: resPic.data.msg})}}).catch(err => {console.log("出错", err)})

整合主要代码如下

<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button><el-dialog :title="title" :visible.sync="editFormVisible" width="35%" @click="closeDialog"><el-form-item label="图片" prop="imgList"><!--          :file-List可以填默认值--><el-uploadaction=""list-type="picture-card"multiple:on-change="handleChange":file-list="imgList":on-error="handleErr"ref="upload":limit="10"accept=".jpg,.png,.jpeg":on-exceed="handleMaxNum":auto-upload="false"><i slot="default" class="el-icon-plus"></i><div slot="file" slot-scope="{file}"><imgclass="el-upload-list__item-thumbnail":src="file.url" alt=""><span class="el-upload-list__item-actions"><spanclass="el-upload-list__item-preview"@click="handlePictureCardPreview(file)"><i class="el-icon-zoom-in"></i></span><spanclass="el-upload-list__item-delete"@click="handleRemove(file)"><i class="el-icon-delete"></i></span></span></div></el-upload></el-form-item></el-form>data() {  imgList: [],
}
methods: {
handleRemove(file) {let arr = this.$refs.upload.uploadFilesconsole.log("arr是",arr)// 2.从pics数组中,找到图片对应的索引值let index = arr.indexOf(file)// 3.调用splice方法,移除图片信息arr.splice(index, 1)this.imgList=arrconsole.log(this.imgList)},handlePictureCardPreview(file) {this.dialogImageUrl = file.url;this.dialogVisible = true;},handleChange(file, fileList) {this.imgList = fileList;},handleMaxNum() {this.$message({type: "info",message: "最多选择10张图片"})},
// 编辑、增加页面保存方法subm**加粗样式**itForm(editData) {this.loading = truethis.$refs[editData].validate(valid => {if (valid) {attractionSave(this.editForm).then(res => {this.editFormVisible = false// console.log(res)if (res.data.success) {let newAttractionId = res.data.attractionId//信息保存成功后,保存图片if ( newAttractionId != '') {let formData = new FormData(); // 用 FormData 存放上传文件// 将图片转为 FormData 格式let promises = [];this.imgList.forEach(item => {let url = item.url;if(url.startsWith("blob")){formData.append('files', item.raw);}else {let promise = fetch(url, {headers: new Headers({'Origin': location.origin}),mode: 'no-cors'}).then(response => response.blob()).then(blob => {// 创建 URL 对象以便提取文件名let filename = url.split('/').pop();// 创建一个虚拟的 File 对象let file = new File([blob], filename, {type: 'image/bmp,image/jpeg,image/png,image/webp'});console.log(file)formData.append('files', file);}).catch(error => {console.error('Failed to fetch image:', error);});promises.push(promise);}});Promise.all(promises).then(() => {console.log("formdata", formData)let uri = "/" + newAttractionIdsaveImgs(uri, formData).then(resPic => {if (resPic.data.success) {// this.$message({//   type:"success",//   message:resPic.data.msg// })} else {this.$message({type: "info",message: resPic.data.msg})}}).catch(err => {console.log("出错", err)})})}this.$message({type: 'success',message: res.data.msg})} else {this.$message({type: 'info',message: res.data.msg})}}).catch(err => {this.editFormVisible = falsethis.loading = falsethis.$message.error('保存失败,请稍后再试!')console.log(err)return false})var that = thissetTimeout(function () {that.loading = false;that.getData()}, 1000)} else {this.loading = falsereturn false}})},//显示编辑界面handleEdit: function (index, row) {this.editFormVisible = trueif (row != undefined && row != 'undefined') {this.title = '修改';this.imgList=row.imgListthis.imgList = this.imgList.map(url => ({url: url,}));console.log("list", this.imgList)} }</el-dialog>

同时,附上SpringBoot业务层代码

  @Overridepublic ResJson savePicture(List<MultipartFile> files, String attractionLocationById) {ResJson resJson = new ResJson();// 获取文件夹中所有文件的列表File file1 = new File(attractionLocationById);File[] folderFiles = file1.listFiles();// 创建一个 HashSet,用于存储上传文件的名称Set<String> uploadedFileNames = new HashSet<>();if(files==null) {for (File folderFile : folderFiles) {if (folderFile.delete()) {System.out.println("删除文件: " + folderFile.getName() + " 成功");} else {System.out.println("删除文件: " + folderFile.getName() + " 失败");}}file1.delete();return null;}for (MultipartFile file : files) {uploadedFileNames.add(file.getOriginalFilename());}System.out.println("uploadedFileNames = " + uploadedFileNames);//删除图片,其实只要全部删除,再重新下载即可,考虑到图片数量可能多,就搞成判断了if(folderFiles!=null) {// 遍历文件夹中的文件for (File folderFile : folderFiles) {String folderFileName = folderFile.getName();// 如果文件夹中的文件不在上传的文件列表中,则删除该文件if (!uploadedFileNames.contains(folderFileName)) {System.out.println(folderFileName);if (folderFile.delete()) {System.out.println("删除文件: " + folderFile.getName() + " 成功");} else {System.out.println("删除文件: " + folderFile.getName() + " 失败");}}else{uploadedFileNames.remove(folderFileName);}}}// 保存上传的文件for (MultipartFile file : files) {try {String originalFilename = file.getOriginalFilename();//如果已经有了,在上面的被移除了,只有在剩下的没被排除内的就下载if(uploadedFileNames.contains(originalFilename)) {// 构建真实的文件路径Path path = Paths.get(attractionLocationById + originalFilename);// 确保目录路径存在Files.createDirectories(path.getParent());// 将上传文件保存到指定位置file.transferTo(path);System.out.println("图片保存成功");System.out.println("保存+1");}resJson.setMsg("图片保存成功");resJson.setSuccess(true);} catch (IOException e) {e.printStackTrace();System.out.println("上传失败");resJson.setMsg("图片保存失败");resJson.setSuccess(false);}}return resJson;}
http://www.lryc.cn/news/332281.html

相关文章:

  • 【拓扑空间】示例及详解1
  • linux安装jdk8
  • Spring重点知识(个人整理笔记)
  • HTML基础知识详解(上)(如何想知道html的全部基础知识点,那么只看这一篇就足够了!)
  • 如何借助Idea创建多模块的SpringBoot项目
  • 爬虫 新闻网站 并存储到CSV文件 以红网为例 V1.0
  • CentOS 使用 Cronie 实现定时任务
  • java生成word
  • C语言中的结构体:揭秘数据的魔法盒
  • Listener
  • 单细胞RNA测序(scRNA-seq)SRA数据下载及fastq-dumq数据拆分
  • 金蝶Apusic应用服务器 未授权目录遍历漏洞复现
  • 成都百洲文化传媒有限公司电商服务的新领军者
  • 从无到有开始创建动态顺序表——C语言实现
  • Unix 网络编程, Socket 以及bind(), listen(), accept(), connect(), read()write()五大函数简介
  • 【附下载】2024全行业数字化转型企业建设解决方案PPT合集
  • 【QT+QGIS跨平台编译】056:【pdal_lepcc+Qt跨平台编译】(一套代码、一套框架,跨平台编译)
  • 蓝桥集训之斐波那契数列
  • 程序员的工资是多少,和曹操有莫大的关系
  • 使用Element Plus
  • 单例(Singleton)设计模式总结
  • LeetCode每日一题之专题一:双指针 ——快乐数
  • Docker Desktop 不支持 host 网络模式
  • Linux网络编程二(TCP图解三次握手及四次挥手、TCP滑动窗口、MSS、TCP状态转换、多进程/多线程服务器实现)
  • 【云原生篇】K8S之Job 和 CronJob
  • PHP8.3-ZTS版本安装流程以及添加扩展
  • RabbitMQ系统监控、问题排查和性能优化实践
  • 【华为OD机试】根据IP查找城市(贪心算法—JavaPythonC++JS实现)
  • css:阴影效果box-shadow
  • Scala第十九章节(Actor的相关概述、Actor发送和接收消息以及WordCount案例)