dom节点:
<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: '文件大小不能超过10MB,请重新上传。',
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作为参数,是后端定义需要传的字段
});
this.$api.uploadFiles(formData).then((res) => { // 调用上传接口
});
}
},
多文件上传时,formData不能做为数组进行上传,他是一个字节流文件,需要把多个文件直接放入到formData里。