我用 formData
发送多个文件像这样
在我的 Spring MVC Controller 中
@PostMapping(value = "/marches")
public Integer saveMarches(
@RequestPart("formJson") FooBean formJson,
@RequestPart("attachOs") MultipartFile[][] attachOs
) throws IOException {
...
}
我的 session :
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(30000000);
return multipartResolver;
}
但我有一个
400 Bad Request
在浏览器中在 IDE 中我得到了:
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'attachOs' is not present]
如果我尝试
@RequestPart("attachOs[][]") MultipartFile[][] attachOs
我总是收到一个错误的请求 Required request part 'attachOs[][]' is not present
问题很明显 : spring 只搜索
attachOs
部分(@RequestPart("attachOs")
),但我发送 attachOs[0][0]
, attachOs[0][1]
...当我只发送
formJson
没有文件的部分,或者如果我只发送一个文件 @RequestPart("attachOs") MultipartFile attachOs
或一维文件数组@RequestPart("attachOs") MultipartFile[] attachOs
一切正常。Javascript代码:
const formData = new FormData();
for (const [i, os] of formJson.os.entries()) {
if(os.attachment) {
for (const [j, file] of [...os.attachment].entries()) {
formData.append(`attachOs[${i}][${j}]`, file );
}
}
}
...
formData.append('formJson',
new Blob([JSON.stringify(formJson)], {type:'application/json'}));
...
axios({
url: ...,
method: 'POST',
data: formData,
})
...
我的
formJson
结构是{
// form fields
...
os: [
{
// os form fields
...
attachment: [{ /* File type */ }, ...], // multiple files per os
},
...
]
}
我知道文件不能与 JSON 一起发送,这就是我在上面构建 formData 的原因,之后我将从 JSON 结构中删除附件属性
所以我的问题:
1. 如何解决错误请求问题?
2. 是否有另一种方法或设计模式来处理这个用例?
最佳答案
如果您想为每个操作系统发送多个文件附件,您可以使用 List
而不是 Spring Controller 中的二维数组。
@PostMapping(value = "/marches")
public Integer saveMarches(
@RequestPart("formJson") FooBean formJson,
@RequestPart("attachOs") List<MultipartFile> files
) throws IOException {
// Associate files with their os using the index in their name.
}
并在您的 Angular 代码中将 os 索引附加到文件名中。
for (const [i, os] of formJson.os.entries()) {
if (os.attachment) {
for (const [j, file] of [...os.attachment].entries()) {
formData.append(`attachOs`, file, file.name + ":" + i );
}
}
}
关于javascript - 发送二维文件数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102594/