Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Rest Jersey : Posting multiple types of data (File and JSON)

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

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?

like image 549
AbuMariam Avatar asked Dec 25 '14 01:12

AbuMariam


1 Answers

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.

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.

Then you can just use @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

Other rreading:

  • General Information on Jersey Multipart support
  • General information on multipart/form-data
  • JAX-RS Post multiple objects

UPDATE

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>
like image 108
Paul Samsotha Avatar answered Sep 30 '22 12:09

Paul Samsotha