Java Rest Jersey: sending multiple data types (file and JSON)

I have a Jersey REST service to which data will be sent. There will be a CSV file, which is the actual data and some metadata for this CSV (meta can be in JSON or XML format). What the method signature should look like and accompany annotations for the service, if they should be published, if it's 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 consider the first parameter as a JSON string of metadata, and the second is an input stream of actual data. Will this work?

+5
source share
1 answer

You should use some multi-page format. It basically consists of one message of type multipart/xxx (where xxx may be something like form-data ), and this message consists of other β€œcomplete” messages with their own content type and other metadata.

You did not specify which version in Jersey, but starting with Jersey 2.xx, there is support for multiple access as 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 this feature, as shown here in the Register section .

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

Here you can see an example of how data can be sent from the client, as well as the multipart internal message format

Other routing:


UPDATE

There is also multipart support in Jersey 1.xx, as this artifact

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

Source: https://habr.com/ru/post/1209861/


All Articles