elementui多选上传 before-upload 格式效验错误总会触发before-remove (elementui多选上传on-success只执行了一次,只上传成功了一条)
今天鹏仔项目中使用elementui做一个批量上传附件时,遇到了以下问题,那么顺便分享一下解决方案。
问题
通过elementui的 :before-upload="beforeAvatarUpload" (上传文件之前的钩子)
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isJPG2 = file.type === 'image/jpg';
const isPNG = file.type === 'image/png';
const isPNG2 = file.type === 'image/bmp';
const isPDF = file.type === 'application/pdf';
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isJPG && !isJPG2 && !isPNG && !isPNG2 && !isPDF) {
this.$message.warning('只支持bmp、jpg、png、pdf格式');
return Promise.reject(isJPG || isJPG2 || isPNG || isPNG2 || isPDF);
}
if (!isLt5M) {
this.$message.warning('请上传5MB以内的文件!');
return Promise.reject(isLt5M);
}
this.loading = true;
return (isJPG || isJPG2 || isPNG || isPNG2 || isPDF) && isLt5M;
},
当上传文件为其他格式,效验格式错误时,总会触发 :before-remove="beforeRemove" (删除文件之前的钩子)
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
},
解决方法
我们只需在 :before-remove="beforeRemove" 事件时判断下当前文件是否为成功的附件即可。
beforeRemove(file, fileList) {
if(file && file.status == 'success'){
return this.$confirm(`确定移除 ${ file.name }?`);
}
},
还有个问题,就是多选文件上传成功时 :on-success="handleAvatarSuccess" (文件上传成功时的钩子) 此方法只会执行一次,多个文件只push到了一条数据。
网上说是把 return false 改为 return Promise.reject(false) 但是我尝试了,还是不起作用!
最终方案如下所示(等所有上传请求完成后,再给fileList进行push赋值)
handleAvatarSuccess(res, file, fileList){
if(fileList.every(it => it.status == 'success')) {
fileList.map(item => {
item.response && this.fileList.push({name:item.name,url:item.response.data,fileName:item.name,fileUrl:item.response.data});
})
}
}
原文 elementui多选上传 before-upload 格式效验错误总会触发before-remove (elementui多选上传on-success只执行了一次,只上传成功了一条)
鹏仔前端 www.pjxi.com

浙公网安备 33010602011771号