【问题记录】ElementUI上传组件使用beforeupload钩子校验失败时的问题处理

一、开发环境

1、Vue 2.5.17

2、ElementUI 2.11.1

二、开发需求

1、支持office文档、图片等格式上传;
2、单文件上传大小限制10MB
3、最多上传20个文件

三、问题描述

假设已经上传了文件A,当再上传下一个文件B时,如果文件B不符合需求,比如大小超过10MB,提示上传失败并将文件B从上传队列中删除,但是同时会将已上传成功的上一个文件A也删除。

代码如下:

 1 <el-upload name="uploadFiles" multiple  
 2  :action="fileUploadAction"  :data="uploadData"  :file-list="fileList" 
 3  :before-upload="beforeFileUpload" 
 4  :on-success="fileUploadSuccess"
 5  :on-remove="fileUploadRemove" 
 6  accept=".jpg,.jpeg,.png,.gif,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.DOC,.XLS,.PPT,.DOCX,.XLSX,.PPTX">
 7      <el-button>
 8          <i class="el-icon-document" />添加附件
 9      </el-button>
10      <span slot="tip" class="el-upload__tip ml-3">
11          支持office文档、图片,单文件上传大小限制10MB,最多上传20个附件        
12       </span>
13 </el-upload>
14 
15 -------------------------------------------------------------------------
16 
17 // 附件上传前校验
18 beforeFileUpload (file) {
19    const isLenLimit = this.fileList.length < 20;
20    const isLt10M = file.size / 1024 / 1024 < 10;
21    if (!isLenLimit) {
22       this.$message.error('最多只能上传20个附件');
23    }
24    if (!isLt10M) {
25       this.$message.error('请上传体积小于10MB的文件');
26    }
27    return isLenLimit && isLt10M;
28 },
29 // 附件删除
30 fileUploadRemove (file) {
31    this.fileList.splice(this.fileList.findIndex(item => item.url === file.url), 1)
32 },

四、解决方法

当文件上传失败的时候,会调用before-remove / on-remove钩子。

根据fileUploadRemove方法,file是上传失败的文件B的信息,此时this.fileList(保存上传成功的文件)中并没有保存文件B,因此findIndex会返回-1,导致最后会删除this.fileList数组中的最后一个数据项。

因此,在执行删除操作的时候,需要添加一些判断,确认文件是否需要被删除。

修改后的代码如下:

1 fileUploadRemove (file) {
2    if(file && file.status==="success"){
3       this.fileList.splice(this.fileList.findIndex(item => item.url === file.url), 1)
4    }
5 }
原文地址:https://www.cnblogs.com/jiafifteen/p/11550769.html