File Upload using JAX-RS RESTful Webservice (Jersey 2.x)

In this tutorial we are going to see about how to upload file using Jersey 2.x RESTful web service.


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

Create maven web application project and add Jersey dependency in pom.xml. Find Jersey 2.x maven dependency configuration below. If you are new to maven refer our maven tutorials.

Jersey 2.x dependency in pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ehowtonow</groupId>
  <artifactId>RestTutorials</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>RestTutorials Maven Webapp</name>
  <url>http://maven.apache.org</url>
   <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>
        
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-multipart -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>${jersey2.version}</version>
</dependency>
        
  </dependencies>
  <build>
    <finalName>RestTutorials</finalName>
  </build>
</project>

You must add jersey-media-multipart maven dependency to upload file using restful webservice.

file-upload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JAX-RS File Upload</title>
</head>
<body>
<form action="rest/fileupload/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload">
</form>
</body>
</html>

FileUploadService.java

package com.ehowtonow.webservice;

import java.io.File;
import java.io.FileOutputStream;
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.core.MediaType;
import javax.ws.rs.core.Response;

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

@Path("fileupload")
public class FileUploadService {

 String response = "";

 @POST
 @Path("upload")
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public Response uploadFile(@FormDataParam("file") InputStream inputStream,
   @FormDataParam("file") FormDataContentDisposition file) {

  try {
	  System.out.println(file.getFileName());
   final String FILE_DESTINATION = "C://ehowtonow//" + file.getFileName();
   File f = new File(FILE_DESTINATION);
   OutputStream outputStream = new FileOutputStream(f);
   int size = 0;
   byte[] bytes = new byte[1024];
   while ((size = inputStream.read(bytes)) != -1) {
    outputStream.write(bytes, 0, size);
   }
   outputStream.flush();
   outputStream.close();

   response = "File uploaded " + FILE_DESTINATION;
  } catch (Exception e) {
   e.printStackTrace();
  }

  return Response.status(200).entity(response).build();
 }
}

In above class @FormDataParam(“file”) used to receive multipart form data.

Configure Jersey 2.x Servlet dispatcher

<!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>Restful Webservice Example</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.ehowtonow.webservice</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>

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

Below init param should be configured in web.xml to enable file upload functionality to Jersey web service .

<init-param>
        	<param-name>jersey.config.server.provider.classnames</param-name>
        	<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
    	</init-param>

If you are failed to configure above init param then you will get org.glassfish.jersey.server.model.ModelValidationException: exception.

javax.servlet.ServletException: Servlet.init() for servlet [jersey-serlvet] threw exception
	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92).....
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response com.ehowtonow.webservice.FileUploadService.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition) at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[multipart/form-data], producedTypes=[], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.ehowtonow.webservice.FileUploadService, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@5b4d0af1]}, definitionMethod=public javax.ws.rs.core.Response com.ehowtonow.webservice.FileUploadService.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition), parameters=[Parameter [type=class java.io.InputStream, source=file, defaultValue=null], Parameter [type=class org.glassfish.jersey.media.multipart.FormDataContentDisposition, source=file, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}']
	org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:554)
	org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:183)
	org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:349)
	org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:346)
	org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
	org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:346)
	org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:339)
	org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
	org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:362)
	javax.servlet.GenericServlet.init(GenericServlet.java:158)
	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)

Ask your questions in eHowToNow Forum

To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

Posts You may Like

  1. How to convert Object to JSON using Jackson 1.x
  2. Java Best Practice – White Spaces
  3. How to change File Last modified Date using Java
  4. How to replace the element from List
  5. Email Receiver using Java Mail API
  6. Log4j Example using Property File
  7. How to search a word inside String
  8. First Java Application in Eclipse
  9. How to create temp file using Java
  10. How to find parent directory of file using Java
  11. How to Create Pretty Print JSON using Jackson
  12. How to validate MAC Address using Java Regular Expression
  13. How to Count number of Element in XML
  14. JAX-RS get QueryParam using @Context UriInfo
  15. JSON Tree Model in Jackson

Be the first to comment

Leave a Reply

Your email address will not be published.


*