本文介绍了Spring引导将多部分文件上传作为json主体的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可能接受包含多部分文件以及其他数据的JSON有效负载的后端点。例如我的身体对象将如下所示:
public class Bio {
private Long id;
private String firstName;
private MultipartFile imageFile;
$ b一个单独但相关的问题是,在springboot文档上传文件的例子中,,该文件是请求路径而不是有效负载。这对我来说似乎很奇怪,所以有办法将文件绑定到请求正文? 解决方案
过去做过的是上传两个单独的部分,一个用于文件,另一个用于附带的JSON。你的控制器方法看起来像这样:
$ b
public void create(@RequestPart(foo )Foo foo,
@RequestPart(image)MultipartFile image)
// ...
}
然后它将使用如下所示的请求:
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 = 图像; filename =foo.png
Content-Type:application / octet-stream
Content-Length:734003
< binary data>
--6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm--
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?
解决方案
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--
这篇关于Spring引导将多部分文件上传作为json主体的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!