3

I'd like to create an endpoint which accepts any amount od different files from user.

For example:

enter image description here

Then, I'd like to receive it in my controller as a Map<String, FilePart> (or any other structure from which I'll know which file is which):

{
    "file1": "cactus-logo.png",
    "file2": "logo.png",
    "file3": "logo.png" (this one is actually different than file2 but has the same name)
}



I tried some combinations of @RequestPart...

  1. When I do:

    @RequestPart Map<String, FilePart> files
    

or

    @RequestPart MultiValueMap<String, FilePart> files

I'm getting:

org.springframework.web.server.ServerWebInputException: 400 BAD_REQUEST "Required request part 'files' is not present"

  1. When I do:

    @RequestPart("files") List<FilePart> files
    

I need to submit files like that:

enter image description here

And then I don't have the information which file is which (if they have the same name):

enter image description here

  1. Finally, I can do:

         @RequestPart("file1") FilePart file1,
         @RequestPart("file2") FilePart file2,
         @RequestPart("file3") FilePart file3
    

And then it works as expected, but with that, it's possible to submit always only 3 files. I'd like to submit any number of files.

  1. As suggested in comments:

         @PutMapping(value = "/{component}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
         public void upload(
              @RequestParam Map<String, MultipartFile> files
         ) throws IOException {
    

and the map is always empty:

enter image description here

enter image description here

Mariusz.v7
  • 2,322
  • 2
  • 16
  • 24
  • See this answer and see whether it helps -> https://stackoverflow.com/questions/4083702/posting-a-file-and-associated-data-to-a-restful-webservice-preferably-as-json#:~:text=Send%20the%20file%20first%20in,an%20ID%20to%20the%20client. – Deviprasad Sharma Sep 13 '20 at 08:12

2 Answers2

2

resultYou should use @RequestParam

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(@RequestParam Map<String, MultipartFile> body) {

}

Then post via form-data media ie:

file1: select file
file2: select file
file3: select file
....
Rony Nguyen
  • 1,067
  • 8
  • 18
0

I did not mention I'm using reactive webflux, thus solution posted by @Toàn Nguyễn Hải does not work in my case. I believe it works in non-reactive applications.

For web flux, the following works:

enter image description here

To be fair, I won't accept any answer, because both of them are fine.

Thanks!

Mariusz.v7
  • 2,322
  • 2
  • 16
  • 24