1

I am trying to upload a file which works fine, the method looks like this:

    @PostMapping("/upload")
    public FileResponse uploadFile(@RequestPart("file") MultipartFile file) {
...

But when I try to upload another json beside it it gets error:

   @PostMapping("/upload")
    public FileResponse uploadFile(@RequestPart("file") MultipartFile file, @RequestBody UserDTO userDTO) {
...

I need UserDTO to verify the user.

Here is my postman snap:

ody

Danial
  • 542
  • 2
  • 9
  • 24
  • your server is refused to accept or request. The HTTP 415 Unsupported Media Type – Akash Jan 02 '20 at 07:37
  • 1
    Probably this can answer all your doubts https://stackoverflow.com/questions/23533355/spring-controller-requestbody-with-file-upload-is-it-possible – Mohit Sharma Jan 02 '20 at 09:35

1 Answers1

1

You won't be able to get both RequestBody and RequestPart in the same controller for multipart request. The workaround I used was to send the object as string and convert it back to object in controller. Eg. below:

@PostMapping(value = "/upload", consumes = {"multipart/form-data"})
public ResponseEntity<Object> upload(
        @RequestParam(required = false, value = "document") MultipartFile document,
        @Valid @RequestParam("userDTOString") String userDTOString) throws JSONException {

    UserDTO userDTO = new ObjectMapper().readValue(userDTOString, UserDTO.class);
    return documentService.uploadFile(document, userDTO);
}
koushikmln
  • 648
  • 6
  • 23