最近在使用element-ui upload 上傳多個文件的時候發現element-ui的批量上傳是每個文件都請求一次接口,但是我們項目的需求是多個文件只請求一次接口.細思良久,經過一番奮戰,終於實現了這個需求.
下面直接上代碼
//element 組件
<el-upload
action=""
class="upload-demo"
:on-change="change"
multiple
:http-request="uploadFile">
<el-button size="small" type="primary">點擊上傳</el-button>
</el-upload>
//data裏面定義一個變量length記錄選擇文件的數量
data() {
return {
length:0,
fileList:[],//文件存儲中間量
}
},
//上傳文件用到的兩個方法
uploadFile(content){
let formData = new FormData();
if(this.fileList.length>0){
this.fileList.forEach(file=> {
formData.append("files", file);
});
if(formData.getAll("files").length == this.length && this.length > 0){
// 走接口
console.log(formData.getAll("files"));
let _url = "*****";//上傳文件接口地址
this.$axios({
url: _url,
method: 'post',
data:formData,
}).then((res) => {
this.fileList=[];
//此處重置文件中間存儲變量是爲了相同文件能夠重複傳遞
if (true === res.data.ok){
this.$message.success(`成功`);
} else {
this.$message.success(`失敗`);
}
}, (err) =>{
this.fileList=[];
this.$message.success(`失敗`);
})
}
}
},
change(){
//判斷上傳文件數量
this.length=document.querySelector("input[type=file]").files.length;
if(this.length>0){
Array.from(document.querySelector("input[type=file]").files).forEach(file=>{
if(this.fileList.indexOf(file) == -1){
this.fileList.push(file);
}
})
}
return false;
},
需要注意的是我們這裏使用的是FormData的格式向後臺傳文件組,後臺定義的格式如圖所示
https://img-blog.csdnimg.cn/20190627170140231.png
![後端定義的字段是files,你們自己可以靈活使用自己後臺定義的字段]
作爲前端的妹子,爲大家貢獻一篇我奮戰好久才解決的問題,僅供大家參考.如果有不同意見和方法,可以互相交流學習