简体   繁体   中英

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. eg 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?

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--

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 "uploadfile=@somevalid.zip" 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.

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