dom節(jié)點(diǎn):
<el-upload
class="upload-demo"
action="#"
:before-remove="beforeRemove"
:before-upload="beforeUpload"
:on-change="uploadChange"
:auto-upload="false"
multiple
:file-list="fileList">
<el-button size="small" type="primary">上 傳</el-button>
</el-upload>
<el-button type="primary" @click="submit">確 定</el-button>
方法:
beforeUpload(file) {
// 獲取上傳文件大小
const imgSize = Number(file.size / 1024 / 1024);
if (imgSize > 10) {
this.$msgbox({
title: '',
message: '文件大小不能超過(guò)10MB纺裁,請(qǐng)重新上傳。',
type: 'warning',
});
return false;
}
return true;
},
beforeRemove(file, fileList) {
const index = fileList.indexOf(file);
this.delIndex = index;
this.fileIds.splice(this.delIndex, 1);
},
uploadChange(file, fileList) { // 這一步一定要寫
this.fileList = fileList;
},
submit() {
if (this.fileList.length) { // 如果有上傳文件
const formData = new FormData();
this.fileList.forEach((item) => {
formData.append('files', item.raw); // 此處一定是append file.raw铁蹈,files作為參數(shù)泵喘,是后端定義需要傳的字段
});
this.$api.uploadFiles(formData).then((res) => { // 調(diào)用上傳接口
});
}
},
多文件上傳時(shí),formData不能做為數(shù)組進(jìn)行上傳秆乳,他是一個(gè)字節(jié)流文件懦鼠,需要把多個(gè)文件直接放入到formData里。