Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot Multipart file upload as part of json body

I'd like to know if it's possible to have a post endpoint that can accept a json payload that contains a multipartfile as well as other data. e.g. my body object would look like:

public class Bio {
    private Long id;
    private String firstName;
    private MultipartFile imageFile;
}

A separate but related question is that in the springboot doc example for uploading a file, https://spring.io/guides/gs/uploading-files/, the file is part of the request path rather than the payload. This seems strange to me so is there a way to have the file bind to the request body?

like image 377
cclusetti Avatar asked Jan 27 '15 20:01

cclusetti


2 Answers

The way I've done this in the past is to upload two separate parts, one for the file and one for the accompanying JSON. Your controller method would look something like this:

public void create(@RequestPart("foo") Foo foo,
        @RequestPart("image") MultipartFile image)
    // …
}

It would then consume requests that look like this:

Content-Type: multipart/mixed; boundary=6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm
--6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm
Content-Disposition: form-data; name="foo"
Content-Type: application/json;charset=UTF-8
{"a":"alpha","b":"bravo"}
--6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm
Content-Disposition: form-data; name="image"; filename="foo.png"
Content-Type: application/octet-stream
Content-Length: 734003
<binary data>
--6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm--
like image 127
Andy Wilkinson Avatar answered Sep 20 '22 15:09

Andy Wilkinson


Andy's solution to use @RequestPart worked perfectly. But not able to validate with postman, as it doesn't seem to support, specifying content type of each multipart to set the boundaries properly as described in his answer.

So to attach both a payload and a file using curl command, some thing like this will do.

curl -i -X POST -H "Content-Type: multipart/mixed" \
-F "somepayload={\"name\":\"mypayloadname\"};type=application/json" \
-F "[email protected]" http://localhost:8080/url

Make sure you escape the payload content and somevalid.zip should be there in the same directory where curl is executed or replace it with valid path to the file.

like image 45
raksja Avatar answered Sep 17 '22 15:09

raksja