Spring boot Multipart file upload as part of json body

后端 未结 2 432
醉梦人生
醉梦人生 2020-12-28 08:36

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 loo

相关标签:
2条回答
  • 2020-12-28 08:56

    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.

    0 讨论(0)
  • 2020-12-28 09:08

    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--
    
    0 讨论(0)
提交回复
热议问题