Maxim Maxim - 2 years ago 256
Java Question

Spring cannot process “multipart/form-data” POST request (error 400 “Bad request”)

when I post request to this server code - everething works good:

@RequestMapping(method = RequestMethod.POST, consumes = { "application/json" })
public ResponseEntity<String> addQuestion(@RequestBody String dtoObject) { ... }


but if I change request to "multipart/form-data" - Spring returns error 400 "Bad request":

@RequestMapping(method = RequestMethod.POST, consumes = { "multipart/form-data" })
public ResponseEntity<String> addQuestion(@RequestBody String dtoObject) { ... }


Why?
May be I should create some extra bean?

PS: I need "multipart/form-data" for sending files together with json objects.

Answer Source

I think you can't deserialize the file to that dtoObject within the request body. you will need to use @RequestPart to do that.

@RequestMapping(method = RequestMethod.POST, consumes = { "multipart/form-data" })
public ResponseEntity<String> addQuestion2(@RequestPart("question") QuestionPostDto dtoObject, @RequestPart("file") MultiPartFile file)  { ... }

your request need to be formdata: with the file you want to upload and json format file question.json

here is my payload example from post man

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="QLbLFIR.gif"
Content-Type: image/gif


------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="question"; filename="question.json"
Content-Type: application/json


------WebKitFormBoundary7MA4YWxkTrZu0gW--

or if you don't want to pass a json format file you can pass it with a normal string

@RequestMapping(method = RequestMethod.POST, consumes = { "multipart/form-data" })
    public ResponseEntity<String> addQuestion2(String question, @RequestPart("file") MultiPartFile file)  {
    QuestionPostDto dtoObject = new ObjectMapper().readValue(request, QuestionPostDto.class); 
    // do sth
}

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="QLbLFIR.gif"
Content-Type: image/gif


------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="request"

{
    "key": "value"
}
------WebKitFormBoundary7MA4YWxkTrZu0gW--

see this thread for more detail: Spring MVC Multipart Request with JSON

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download