项目场景:
- 前端:Vue3 + ts + elementui plus
- 后端:springboot
问题描述
在前端上传form表单时,上传的数据为[object Object]
同时后端报错:
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present
原因分析:
后端代码:
public ResponseData<?> importGeoData(@RequestParam("parentAdcode") @NotNull String parentAdcode, @RequestParam("file") MultipartFile file) throws Exception { GeoUploadRequest uploadRequest = new GeoUploadRequest(); uploadRequest.setParentAdcode(parentAdcode); uploadRequest.setFile(file); return getResult(geoDataService.importGeoData(uploadRequest)); }
由于apifox中上传正常,所以排除后端问题,检查前端代码
查看前端代码:
const file = uploadFileList.value[i]; console.log(file) formData2.append('file', file); formData2.append('parentAdcode', formData.parentAdcode); importObjects(formData2).then(res=>{ ElMessage.success('导入成功') })
这里打印的file:
发现file内部还有一个raw属性,我们要上传的是这个raw里面的内容
解决方案:
更改前端代码如下:
const file = uploadFileList.value[i]; formData2.append('file', toRaw(file.raw)); formData2.append('parentAdcode', formData.parentAdcode); importObjects(formData2).then(res=>{ ElMessage.success('导入成功') })
再次查看payload:
发送的数据正确,同时后端正确处理请求