Java Rest Jersey:发布多种类型的数据(文件和 JSON)多种、类型、文件、数据

2023-09-06 11:12:36 作者:埋葬 、 爱情

我有一个将发布数据的 Jersey REST 服务.将有一个 CSV 文件,它是实际数据和该 CSV 的一些元数据(元数据可以是 JSON 或 XML 格式).如果这两个都需要发布,服务的方法签名和伴随注释应该是什么样子,应该是......

I have a Jersey REST service to which data will be posted. There will be a a CSV file which is the actual data and some meta-data for that CSV (the meta can either be in JSON or XML format). How should the method signature and accompany annotations for the service look like if both of these need to be posted, should it be something like...

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({MediaType.APPLICATION_JSON})
public CreateTaskVO provideService(@FormParam("meta") String v1,
        @FormParam("data") InputStream v2) {

在这里,我设想第一个参数是元数据的 JSON 字符串,第二个参数是实际数据的输入流.这行得通吗?

Here I am envisioning the first parameter to be a JSON string of meta-data and the second an input stream of the actual data. Would this work?

推荐答案

你应该使用一些多部分格式.它基本上由 multipart/xxx 类型的单个消息组成(其中 xxx 可以是 form-data 之类的东西),并且该消息由其他具有自己的内容类型和其他元数据的完整"消息.

You should use some multipart format. It basically consists of a single message of type multipart/xxx (where xxx can be something like form-data), and that message consists of other "complete" messages with their own content-type and other meta data.

您尚未指定 Jersey 版本,但从 Jersey 2.x.x 开始,有可用的多部分支持,以单独工件的形式:

You haven't specified which Jersey version, but starting with Jersey 2.x.x, there is multipart support available, in the form of a separate artifact:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>${jersey.version}</version>
</dependency>

然后您只需要注册该功能,如 在此处注册.

Then you just need to register the feature, as seen here in Registration.

那么你可以使用 @FormDataParam

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({MediaType.APPLICATION_JSON})
public CreateTaskVO provideService(
               @FormDataParam("meta") String jsonMeta,
               @FormDataParam("data") InputStream file,
               @FormDataParam("data") FormDataContentDisposition fileDetail) {

您可以查看此处的示例如何从客户端发送数据,以及内部消息正文多部分的格式

You can see here an example of how the data can be sent from the client, and also the internal message body format of a multipart

其他阅读:

关于 Jersey Multipart 支持的一般信息关于 multipart/form 的一般信息-数据JAX-RS 发布多个对象

更新

Jersey 1.x.x 中也支持多部分,以 this artifact 的形式

There is also support for multipart in Jersey 1.x.x, in the form of this artifact

<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>${jersey.version}</version>
</dependency>