先上代码
<template>
<el-form
id="upload-tool"
ref="form"
:model="form"
label-width="120px"
labelPosition="left">
<el-form-item :label="$t('tools.file')" prop="docFile">
<el-upload
ref="uploadDocFile"
action="/service/application"
:http-request="doNothing"
:on-change="addDocFile"
:before-upload="beforeUploadDocFile"
:on-remove="removeDocFile"
multiple
:limit="5"
:on-exceed="handleExceed">
<el-button size="small" type="primary">{{$t('tools.addFile')}}</el-button>
<div class="el-upload__tip" slot="tip">{{$t('tools.docLimit')}}</div>
</el-upload>
</el-form-item>
<el-form-item class="submitItem">
<el-button type="primary" @click="onSubmit">{{$t('tools.submit')}}</el-button>
</el-form-item>
</el-form>
</template>
<script>
import {mapActions} from 'vuex';
export default {
name: 'tools-upload-new',
data() {
return {
form: {
docFile: [],
}
};
},
methods: {
...mapActions('tool', ['uploadTool']),
doNothing() {
// 为了使用上传文件之前的钩子before-upload,自定义此空函数,而不是设置auto-upload为false。
},
addDocFile(file, fileList) {
if (this.isPdf(file)) {
return;
}
if (file.status === 'ready') {
this.form.docFile.push(file.raw);
}
},
beforeUploadDocFile(file) {
const maxFileBytes = 400 * 1024 * 1024;
const isSizeFit = file.size <= maxFileBytes;
if (!isSizeFit) {
this.$message.error(this.$t('tools.fileLimit'));
}
return isSizeFit;
},
removeDocFile(file, fileList) {
let index = this.form.docFile.indexOf(file.raw);
this.form.docFile.splice(index, 1);
},
handleExceed(files, fileList) {
this.$message.warning(this.$t('tools.uploadFileNumTip'));
},
reset() {
this.$refs.form.resetFields();
this.$refs.uploadDocFile.clearFiles();
},
onSubmit() {
this.$refs.form.validate(valid => {
if (!valid) {
return false;
}
this.uploadTool(Object.assign({}, this.form))
.then(() => {
this.$message.success(this.$t('tools.uploadSuccess'));
this.reset();
})
.catch(code => {
this.$message.error(this.$t('tools.uploadFailed'));
});
});
}
}
};
</script>
可以看到在提交前,form.docFile的内容为
1.png
如果就这样直接提交,后台是接收不到docFile的值的
用springboot做后台,使用 MultipartFile[] 接收多文件
12320369-96530151799a38ce.png
在发post请求前,使用formData
往docFile赋予多值formData.append('docFile', file)
upload(data) {
let method = 'POST';
let uploadUrl = userfileUrl + '/upload';
let body = new FormData();
Object.keys(data).forEach(key => {
if (key === 'docFile') {
for (let value of data[key]) {
body.append(key, value);
}
} else {
body.append(key, data[key]);
}
});
console.log('docFile', body.getAll('docFile'));
return api.fetch({url: uploadUrl, method, body, file: true});
},
打印出来看看docFile
3.png
可以看到,我们的form.docFile,和我们现在打印出来的formData的docFile不一样,
formData里面是File[]数组
可以用 MultipartFile[] 接收到
结论
使用 formData
来实现多文件一次性上传
比如要传多文件的字段为 "file[]"
那么 formData.append('file[]', file)
即可
网友评论