el-upload控件一次接口請求上傳多個文件


el-upload組件默認情況下上傳多少個文件就會請求多少次上傳接口,如何一次上傳多個文件而不必多次請求上傳接口呢?直接看代碼

html

<el-upload :action="actionUrl" :auto-upload="false" :multiple="true" :file-list="fileList" :on-change="onChange" :on-remove="onRemove" :on-exceed="OnExceed" ref="upload" list-type="picture" :limit="10">
<button>上傳附件文檔</button>
<span>注意:支持jpg,png格式</span>
</el-upload>

js 

onChange(file, fileList) { //這里做一些文件控制,注意:就算一次選取多個文件,這里依舊會執行多次
  const isJPG = file.raw.type === 'image/jpeg';
  if (!isJPG) {
    this.$message.error('上傳頭像圖片只能是 JPG 格式!');
    fileList.pop()
  }
  let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
  if (existFile) {
    this.$message.error('當前文件已經存在!');
    fileList.pop()
  }
  this.fileList = fileList
},

onRemove(file, fileList) {
  this.fileList = fileList
},

OnExceed(file, fileList) {
  this.$message.error(`最多只能上傳10張圖片!`);
},

submitUpload() {   //上傳函數,如果把提交函數用在http-request鈎子中,fileList多長就執行請求多少次接口,依舊是無法做到只請求一次上傳多文件
  var formData = new FormData();  //  用FormData存放上傳文件
  this.fileList.forEach(file => { 
      formData.append(
'reportFile', file.raw, file.raw.name); //此處一定是append file.raw 上傳文件只需維護fileList file.raw.name要加上
  })
  uploadFiles(formData).then(res
=> { //手動上傳貌似無法觸發成功或失敗的鈎子函數,因此這里手動調用
  this.onSuccess()
}).
catch(err => {
   console.log(err)
  
this.onError()
})
}

 一些注意的關鍵點都已經寫在注釋了,還有一點需要注意的,如果把el-upload用在el-form內,點擊上傳的時候回刷新路由,目前還沒找到解決辦法,以上都是踩的一些小坑,希望對大家有幫助!!!

 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM