java Spring boot Multipart文件上传作为json主体的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28179251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring boot Multipart file upload as part of json body
提问by cclusetti
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:
我想知道是否有可能有一个可以接受包含多部分文件和其他数据的 json 有效负载的 post 端点。例如我的身体对象看起来像:
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?
一个单独但相关的问题是,在用于上传文件的 springboot 文档示例https://spring.io/guides/gs/uploading-files/ 中,该文件是请求路径的一部分,而不是有效负载。这对我来说似乎很奇怪,所以有没有办法将文件绑定到请求正文?
回答by Andy Wilkinson
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:
我过去这样做的方法是上传两个单独的部分,一个用于文件,另一个用于随附的 JSON。您的控制器方法如下所示:
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--
回答by raksja
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.
安迪使用@RequestPart 的解决方案非常有效。但无法使用邮递员进行验证,因为它似乎不支持,指定每个多部分的内容类型以按照他的回答中的描述正确设置边界。
So to attach both a payload and a file using curl command, some thing like this will do.
所以要使用 curl 命令附加有效载荷和文件,这样的事情就可以了。
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.
确保您转义了有效负载内容,并且 somevalid.zip 应该位于执行 curl 的同一目录中,或者将其替换为文件的有效路径。