Multipart file upload client for RESTFul web service (java/ jersey/example)

By | January 17, 2016

Multipart file upload client is capable of uploading different kind of files to RESTFul web service using Jersey framework.

1. What is objective of Multipart file Upload client using jersey ?

  • File upload client using “multipart/mixed” mime type.
  • We have upload the following file formats to be RESTFul web service
    • JPG
    • JSON
    • PDF
    • zip

We have discussed RESTFul multipart web service  using spring framework. We have tested the Multipart file upload client with RESTFul multipart web service . We can download the web service project from above link, to check the end to end flow of applications.

We have used “http://localhost:9095/multipart/file/upload” (we will discuss shortly) to upload files to web service. Where “/multipart” defines the context path, where web service is is being deployed. We can change the above url as per our web service deployment.

2. Jersey client maven dependencies:


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

3. Multipart file upload Jersey client – RESTFul web service example (java)

3.1.) Application class:

The application class contains the main function. Application class performing following operations:

  • Create the different file resource, which we will send to RESTFul web service (linked shown earlier).
  • We are uploading following files format.
    • JPG
    • PDF
    • JSON
    • RAR (zip format)
  • We are calling JerseyFileUpload.uploadFiles method to upload files files.
  • We have “http://localhost:9095/multipart/file/upload” of RESTFul web service to upload files.

import java.io.File;
public class Application {
	public static void main(String[] args) {
		try {
			String url = "http://localhost:9095/multipart/file/upload";
			File imgFile = new File("src/main/resource/img.jpg");
			File pdfFile = new File("src/main/resource/SamplePdf.pdf");
			File jsonFile = new File("src/main/resource/Organization.json");
			File zipFile = new File("src/main/resource/SoftwareData.rar");
			
			JerseyFileUpload.postFile(url,imgFile,pdfFile,jsonFile,zipFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

3.2.) JerseyFileUpload class:

JerseyFileUpload class is responsible for uploading multipart contents to REST web service.

  1. Create a client with MultiPartFeature enabled.
  2. Add multi part contents like pdf, image, text etc to multipart object.
  3. Execute post request to invoke RESTFul resource.
  4. Parse the response and display the execution result.


package org.learn.FileUpload;

import java.io.File;
import java.io.IOException;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;

public class JerseyFileUpload {
	private final static String contentType = "multipart/mixed";

	public static void postFile(String serverURL, File imgFile, File pdfFile, 
													File jsonFile, File zipFile) {
		MultiPart multiPart = null;
		try {
			Client client = ClientBuilder.newBuilder().
								register(MultiPartFeature.class).build();
			WebTarget server = client.target(serverURL);
			multiPart = new MultiPart();

			FileDataBodyPart pdfBodyPart = new FileDataBodyPart("pdfFile", pdfFile,
					MediaType.APPLICATION_OCTET_STREAM_TYPE);
			FileDataBodyPart imgBodyPart = new FileDataBodyPart("imgFile", imgFile,
					MediaType.APPLICATION_OCTET_STREAM_TYPE);
			FileDataBodyPart jsonBodyPart = new FileDataBodyPart("jsonFile", jsonFile,
					MediaType.APPLICATION_OCTET_STREAM_TYPE);
			FileDataBodyPart zipBodyPart = new FileDataBodyPart("zipFile", zipFile,
					MediaType.APPLICATION_OCTET_STREAM_TYPE);
			// Add body part
			multiPart.bodyPart(pdfBodyPart);
			multiPart.bodyPart(imgBodyPart);
			multiPart.bodyPart(jsonBodyPart);
			multiPart.bodyPart(zipBodyPart);

			Response response = server.request(MediaType.APPLICATION_JSON_TYPE)
					.post(Entity.entity(multiPart, contentType));
			if (response.getStatus() == 200) {
				String respnse = response.readEntity(String.class);
				System.out.println(respnse);
			} else {
				System.out.println("Response is not ok");
			}
		} catch (Exception e) {
			System.out.println("Exception has occured "+ e.getMessage());
		} finally {
			if (null != multiPart) {
				try {
					multiPart.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

4. O/P: Jersey multipart file upload client -RESTFul web service (example)


uploaded files :[img.jpg, SamplePdf.pdf, Organization.json, SoftwareData.rar]

Download Code – Jersey multipart file upload client RESTFul web service

  • Jeet Singh

    Hi Team,

    Thanks for your post its really very helpful !!

    I have same requirement but that URL needs basic authentication how can I add basic authentication with this code?

    Thanks,
    Jeet

    • Admin

      Dear Jeet,

      In near future, we will create a separate post for basic authentication.
      Please modify the code to add basic authentication feature.

      HttpAuthenticationFeature basicAuth = HttpAuthenticationFeature.basic(“AddUserName”, “AddPassword”);
      Client client = ClientBuilder.newBuilder().
      register(basicAuth).
      register(MultiPartFeature.class).
      build();

      Kindly do let us know, if you face any issues.

      Thanks,
      Admin