默认是异步多次请求上次单个文件
如果业务就是单纯的上传文件,那么这个样子是没有问题的
前端代码参考
https://element-plus.gitee.io/#/zh-CN/component/upload
后端接口
@RequestMapping("upload")
@ResponseBody
public CommonVO fileUpload(@RequestParam("file") MultipartFile multipartFile) {
但如果你的业务是上传文件的同时插入数据库内容的话,那么就会有问题
比如以下代码
@RequestMapping("upload")
@ResponseBody
public CommonVO fileUpload(@RequestParam("file") MultipartFile multipartFile, String trainName, String trainContent) {
// 内部逻辑为保存multipartFile文件,并数据库保存trainName,trainContent
return staffTrainService.saveTrainAndUpload(multipartFile,trainName,trainContent);
}
此时由于发了两次请求,导致同样的数据被保存多次
如果要解决这种情况,还需后端进行同步,然后去判断内容有没有被保存过(这也不好进行判断)
所以最好的情况就是前端只发送一次请求
前端最重要的就是el-upload中的:http-request,这个是让我们自定义上传方法
当然还有取消自动上传:auto-upload="false"
<html>
<head></head>
<body>
<el-upload class="upload-demo" ref="upload" action="/manager/staffTrain/upload" :on-preview="handlePreview" :on-change="handleChange" :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" :data="dataModel" :on-success="handleSuccess" :http-request="uploadFile">
<template #trigger="">
<el-button size="small" type="primary">
选取文件
</el-button>
</template>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" v-show="false">
发 布
</el-button>
</el-upload>
</body>
</html>
data() {
return {
// 这是上传文件的同时携带的数据
dataModel: {
trainName: ‘‘,
trainContent: ‘‘,
},
// 文件上传
fileData: ‘‘, // 文件上传数据(多文件合一)
fileList: [], // upload多文件数组
}
},
methods: {
// 覆盖上传事件,选择文件之后触发的事件
uploadFile(file) {
this.fileData.append(‘files‘, file.file); // append增加数据
},
// 点击上传后触发的事件
submitUpload() {
if (this.dataModel.trainName === ‘‘) {
this.message({
message: ‘请输入培训名称‘,
type: ‘warning‘
})
} else {
const isLt100M = this.fileList.every(file => file.size / 1024 / 1024 < 100);
if (!isLt100M) {
this.$message.error(‘请检查,上传文件大小不能超过100MB!‘);
} else {
this.fileData = new FormData(); // new formData对象
this.$refs.upload.submit(); // 提交调用uploadFile函数
this.fileData.append(‘trainName‘, this.dataModel.trainName); // 添加培训名称
this.fileData.append(‘trainContent‘, this.dataModel.trainContent); // 添加培训内容
this.postRequest("/manager/staffTrain/upload", this.fileData).then((resp) => {
if (resp.success) {
this.fileList = [];
this.addDialogVisible = false;
//清空表单
this.$refs[‘addForm‘].resetFields();
this.getTableData(this.pageNo, this.pageSize);
}
});
}
}
},
//监控上传文件列表
handleChange(file, fileList) {
let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name);
if (existFile) {
this.message.error(‘当前文件已经存在!‘);
fileList.pop();
}
this.fileList = fileList;
},
},
这时候就可以直接接受一整个multipartFiles数组了
@RequestMapping("upload")
@ResponseBody
public CommonVO fileUpload(@RequestParam("files") MultipartFile[] multipartFiles, String trainName, String trainContent) {
return staffTrainService.saveTrainAndUpload(multipartFiles,trainName,trainContent);
}
原文:https://www.cnblogs.com/flower1360/p/14638370.html