问题:
前端代码
html
<a-form-item name="upload" label="音/视频文件上传" extra="" >
<a-upload
v-model:file-list="fileList2"
:max-count="50"
multiple="'true"
:before-upload="beforeUpload2"
@remove="handleRemove2"
@change="handleUpload2"
action="/api/v1/file/upload"
>
<a-button>
<upload-outlined></upload-outlined>
点击上传(最大数量50)
</a-button>
</a-upload>
</a-form-item>
js
const handleRemove2 = file => {
const index = fileList2.value.indexOf(file)
const newFileList = fileList2.value.slice()
newFileList.splice(index, 1)
fileList2.value = newFileList
}
const beforeUpload2 = file => {
fileList2.value = [...fileList2.value, file]
return false
}
const handleUpload2 = async () => {
let that = this;
const formData = new FormData()
fileList2.value.forEach(file => {
console.log(file)
// 注意这里append的名字“file”,需要跟后端接受的名字是一样的
formData.append('file', file)
})
fileUpload(formData).then((res) => {
const data = res.data;
if(res.status ==200 ){
formState.fileList.push( data.data);
console.log(JSON.stringify("fileList",formState.fileList))
}else {
message.error("文件上传失败!");
}
}).catch((error) => {
});
}
后端
@PostMapping("upload")
public CommonResult<Map> uploadFile(@RequestParam("file") MultipartFile file) {
logger.info("文件上传!");
CommonResult<Map> result = new CommonResult<Map>();
try {
Map<String, Object> upload = filesService.uploadFile(file);
result.setData(upload);
result.setCode(ResultConstants.SUCCESS);
} catch (IOException e) {
e.printStackTrace();
result.setCode(ResultConstants.ERROR);
}
return result;
}
以上代码会出现报错信息
2022-08-14 09:35:47.649 WARN 15092 --- [nio-8007-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
解决办法:
将前端的js中的
handleUpload2
这部分代码的
formData.append('file', file)
修改为
formData.append('file', file.originFileObj)
问题得到解决