When I send multiple files using formData
, it's structured like this:
https://i.sstatic.net/BjePq.png
Within my Spring MVC Controller:
@PostMapping(value = "/marches")
public Integer saveMarches(
@RequestPart("formJson") FooBean formJson,
@RequestPart("attachOs") MultipartFile[][] attachOs
) throws IOException {
...
}
My configuration is:
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(30000000);
return multipartResolver;
}
However, I encountered a 400 Bad Request
error in the browser:
https://i.sstatic.net/18p0n.png
And in my IDE, I received the following error message:
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'attachOs' is not present]
When I tried using
@RequestPart("attachOs[][]") MultipartFile[][] attachOs
, I still received a bad request error with Required request part 'attachOs[][]' is not present
The problem is clear: Spring is only looking for the attachOs
part (@RequestPart("attachOs")
), but I am sending attachOs[0][0]
, attachOs[0][1]
, and so on.
When I send just the formJson
part without files, or if I send a single file using
@RequestPart("attachOs") MultipartFile attachOs
or an array of files using @RequestPart("attachOs") MultipartFile[] attachOs
, everything works correctly.
Here is the JavaScript code I am using:
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,
})
...
The structure of my formJson
is as follows:
{
// form fields
...
os: [
{
// os form fields
...
attachment: [{ /* File type */ }, ...], // multiple files per os
},
...
]
}
I am aware that files cannot be sent along with JSON, which is why I construct the formData as shown above, and then remove the attachment property from the JSON structure.
So, my questions are:
1. How can I resolve the bad request issue?
2. Is there an alternative approach or design pattern to handle this use case?