简体   繁体   中英

Spring boot unsupported media type with multipart request

I am trying to send a file and two json objects to my Spring Boot backend with a multipart POST request but I always get a 415 http response. Here is a list of things that I already tried to do:

  1. Send each object as a Blob file with an application/json content type as suggested here
  2. Send each object as a String as suggested here
  3. Add contentType: false and processData: false in the ajax request as suggested here
  4. Use @RequestParam instead of @RequestPart in Spring Boot controller

What am I missing?

Here is the request:

const data = new FormData();
data.append('file', new Blob([file], {type: 'multipart/form-data'}));
data.append('entity1-info', new Blob([JSON.stringify(entity1Object)], {type: 'application/json'}));
data.append('entity2-info', new Blob([JSON.stringify(entity2Object)], {type: 'application/json'}));

return axios({
   method: 'post',
   url: url,
   headers: {'Authorization': `Bearer ${idToken}`},
   data: data,
   contentType: false,
   processData: false
});

And here is my controller in Spring Boot:

@PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@NotEmpty @RequestPart("file") MultipartFile multipartFile, @NotNull @RequestPart("entity1-info") Entity1 entity1, @NotNull @RequestPart("entity2-info") Entity2 entity2, HttpServletRequest request) {
        log.debug(request);
        ...
        return ResponseEntity.ok("ok");
    }

You have to set the "Content-Type" to the header

Content-Type:multipart/form-data

I'm using similar to the below curl command and it's working fine.

curl -v -H "Content-Type:multipart/form-data" -F "entiry1-info=@person1;type=application/json" -F "entiry2-info=@person2;type=application/json" -F "file=@logo.png;type=multipart/form-data" -X POST http://<IP_Address>:8080/api/upload

Note: above person1 and person2 are json files.

I eventually found the reason why I was always getting 415 http response from my Spring Boot backend.

The problem was that the url of the request was wrong. It was pointing to an endpoint that was expecting only json data and not multipart. And that's why Spring Boot was returning Unsupported media type .

Hope this could help someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM