HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Jersey / Multi-file Upload

Jersey – Ajax Multi-File Upload Example

Learn to use Ajax with JAX-RS webservices (Jersey used in example) to upload multiple files with single button click. Also look at form based file upload example and file download example as well.

Jersey multi-file upload success

Table of Contents

Jersey maven multipart dependency
Add MultiPartFeature
Write Upload REST API
HTML/Ajax code
Demo of Multiple files upload

Jersey maven multipart dependency

To use multipart features you need to add jersey-media-multipart module to your pom.xml file along with other required modules.

<project xmlns="http://maven.apache.org/POM/4.0.0" 
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
		 http://maven.apache.org/xsd/maven-4.0.0.xsd;
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.howtodoinjava.jersey</groupId>
	<artifactId>JerseyDemos</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<repositories>
		<repository>
			<id>maven2-repository.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/2/</url>
			<layout>default</layout>
		</repository>
	</repositories>
	<properties>
		<jersey2.version>2.19</jersey2.version>
		<jaxrs.version>2.0.1</jaxrs.version>
	</properties>
	<dependencies>
		<!-- JAX-RS -->
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>${jaxrs.version}</version>
		</dependency>
		<!-- Jersey 2.19 -->
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-server</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-multipart</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>JerseyDemos</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Add MultiPartFeature

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.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

	<display-name>Archetype Created Web Application</display-name>

	<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.filter.LoggingFilter;
						 org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

</web-app>

Write Upload REST API

Now write the service layer JAX-RS API which will actually have the logic to store the uploaded file on server.

package com.howtodoinjava.jersey;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/upload")
public class JerseyService 
{
	@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(fileMetaData.getFileName() + " uploaded successfully !!").build();
	}
}

HTML/Ajax code

Time to look at client side code. I have written a very simple file with minimal functionality. Let me know if you want some specific changes in it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
		<meta content="utf-8" http-equiv="encoding" />

		<script src="./js/jquery.min.js"></script>
		<script type="text/javascript">

		$(document).ready(function() 
		{
			$("#uploadBtn").click(function() 
			{
				$('input[name="file"]').each(function(index, value) 
				{ 
				    var file = value.files[0];
				    if(file) 
				    {
				    	var formData = new FormData();
						formData.append('file', file);
						$.ajax({
						  url : '/JerseyDemos/rest/upload/pdf',
						  type : 'POST',
						  data : formData,
						  cache : false,
						  contentType : false,
						  processData : false,
						  success : function(data, textStatus, jqXHR) {
						    	var message = jqXHR.responseText;
						    	$("#messages").append("<li>" + message + "</li>");
						  },
						  error : function(jqXHR, textStatus, errorThrown) {
							  	$("#messages").append("<li style='color: red;'>" + textStatus + "</li>");
						  }
						});
					}
				});
			});
		});
		</script>
</head>
<body>
	<h1>JAX-RS Multi-file Upload Example</h1>

	<form action="rest/upload/pdf" method="post" enctype="multipart/form-data">

		<p>
			Select file 1: <input type="file" name="file" size="45"	accept=".pdf" />
		</p>
		<p>
			Select file 2: <input type="file" name="file" size="45"	accept=".pdf" />
		</p>
		<p>
			Select file 3: <input type="file" name="file" size="45"	accept=".pdf" />
		</p>
		<p>
			<input id="uploadBtn" type="button" value="Upload PFD Files" />
		</p>

	</form>
	
	<ul id="messages">	
	</ul>

</body>
</html>

Demo of Multiple files upload

Demo time. Deploy the application on server and hit the URL : http://localhost:8080/JerseyDemos/fileUpload.html

Jersey multifile upload example - blank form
Jersey multifile upload example – blank form

Now select two/three files and click on upload button. You will get below message on screen. And files will be stored on server too.

Jersey multi-file upload success
Jersey multi-file upload success

Let me know of your questions in comment box.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Rajesh

    May 3, 2017

    hi the format in the code snippet is not relevant, could you please look in to that, its quite difficult to figure out the exact code

    • Lokesh Gupta

      May 3, 2017

      Done

  2. Shahin

    November 23, 2015

    Hi. I am trying to compare two files that are uploaded to the server and return the result to the html. So i need an ajax code that will send the two files to the same service. How to do this using jersey+ajax. Thanks in advance.

Comments are closed on this article!

Search Tutorials

Jersey Tutorial

  • Jersey – Hello World
  • Jersey2 – Hello World
  • Jersey – quickstart-archetype
  • Jersey – Custom Logging
  • Jersey – Set Cookie
  • Jersey – File Download
  • Jersey – File Upload
  • Jersey – Multi-File Upload
  • Jersey – Exception Handling
  • Jersey – MOXy JSON
  • Jersey – JSONP
  • Jersey – Google Gson
  • Jersey – Security

Jersey Client

  • Jersey Client – Access REST APIs
  • Jersey Client – Authentication
  • Jersey Client – Set Cookie

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)