多个文件上传时,需要逐个将文件参数添加到formData中,如
if (val.file) {
val.file.map(x => formData.append('file', x.originFileObj));
}
后台的接口参数需写成
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result<Boolean> applyMulti(@RequestPart(required = false, value = "file") MultipartFile[] fileArray,
@RequestParam(name = "id") Long id,
// 省略...
HttpServletRequest request} {
// 省略...
}
@RequestPart(required = false, value = "file") ,允许不包含文件
@RequestPart 与 @RequestParam 的区别如下
1 @RequestPart 用在 multipart/form-data 表单提交请求的方法上
2 支持的请求方法的方式MultipartFile,属于Spring的MultipartResolver类,这个请求是通过http协议传输的
3 @RequestParam也同样支持multipart/form-data请求
4 他们最大的不同是,当请求方法的请求参数类型不再是String类型的时候:@RequestParam适用于name-valueString类型的请求域,@RequestPart适用于复杂的请求域(像JSON,XML)
当 form-data 表单包含多个对象组成的数组,直接放入formData时,无论后台使用 @RequestPart 还是 @RequestParam,即便类型为String接收,都会报错:
org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.List'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com....QueryVo': no matching editors or conversion strategy found
或
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported
前端需要以 json 格式传递此数组,而文件上传的格式为 multipart/form-data,要怎么才能同时传递 json 格式的数据呢?如下
if (attachmentList && attachmentList.length > 0) {
// 以json格式传递此集合参数
formData.append(
'attachmentList',
new Blob([JSON.stringify(attachmentList)], { type: 'application/json' })
);
}
后台接收参数为
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result<Boolean> applyMulti(@RequestPart(required = false, value = "file") MultipartFile[] fileArray,
@RequestParam(name = "id") Long id,
// ...省略
@RequestPart(required = false, value = "attachmentList") List<对象Vo> attachmentList,
HttpServletRequest request) {
// 省略...
}