Jersey file upload example – jersey 2 MultiPartFeature

In this Jersey 2 file upload example, we will be learning to upload binary files (e.g. PDF files in this example) using Jersey’s multipart form data support. We will learn below required changes to complete the functionality.

Table of Contents

1. Jersey maven multipart dependency
2. Add MultiPartFeature in web.xml
3. Write Jersey Upload REST API
4. Test file upload using HTML Form
5. Test file upload using jersey client

1. Jersey maven multipart dependency

To use multipart features you need to add jersey-media-multipart module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>2.19</version>
</dependency>

2. Add Jersey MultiPartFeature in web.xml

Further, you are required to add MultiPartFeature in Jersey configuration to let it know that you will use multipart requests. Simplest way is to add support through web.xml file.

<servlet>
	<servlet-name>jersey-serlvet</servlet-name>
	<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
	<init-param>
		<param-name>jersey.config.server.provider.packages</param-name>
		<param-value>com.howtodoinjava.jersey</param-value>
	</init-param>
	<init-param>
		<param-name>jersey.config.server.provider.classnames</param-name>
		<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

3. Write Jersey File Upload REST API

Now look at actual REST API for file upload, which will receive and save the file.

@POST
@Path("/pdf")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadPdfFile(	@FormDataParam("file") InputStream fileInputStream,
        						@FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception
{
	String UPLOAD_PATH = "c:/temp/";
	try 
	{
		int read = 0;
		byte[] bytes = new byte[1024];

		OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileMetaData.getFileName()));
		while ((read = fileInputStream.read(bytes)) != -1) 
		{
			out.write(bytes, 0, read);
		}
		out.flush();
		out.close();
	} catch (IOException e) 
	{
		throw new WebApplicationException("Error while uploading file. Please try again !!");
	}
	return Response.ok("Data uploaded successfully !!").build();
}

5. Test file upload using HTML Form

Simply create a file ‘fileUpload.html‘ file in ‘webapp‘ folder and paste this code.

<html>
	<body>
		<h1>File Upload Example - howtodoinjava.com</h1>
	
		<form action="rest/upload/pdf" method="post" enctype="multipart/form-data">
	
			<p>Select a file : <input type="file" name="file" size="45" accept=".pdf" /></p>
			<input type="submit" value="Upload PDF" />
			
		</form>
	
	</body>
</html>

Now hit the URL : “http://localhost:8080/JerseyDemos/fileUpload.html” and it will display a HTML file control to browse the file. Select any PDF file and click on “Upload PDF” button.

Your file will be uploaded and you will get the message: “Data uploaded successfully !!”

5. Test file upload using jersey client

If you are looking for uploading files using java clients then you can modify below working code as per your need.

Jersey file upload using FormDataMultiPart example.

public static void main(String[] args) throws IOException 
{
	final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();

	final FileDataBodyPart filePart = new FileDataBodyPart("file", new File("C:/temp/sample.pdf"));
	FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
	final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo", "bar").bodyPart(filePart);
	 
	final WebTarget target = client.target("http://localhost:8080/JerseyDemos/rest/upload/pdf");
	final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType()));
	
	//Use response object to verify upload success
	
	formDataMultiPart.close();
	multipart.close();
}

Drop me your questions in comments box related to jersey 2 multipart file upload example.

Happy Learning !!

Reference : https://jersey.java.net/documentation/latest/user-guide.html#multipart

Comments

Subscribe
Notify of
guest
16 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode