一、開發環境
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 }
