Tuesday 22 September 2015

Jersey 2 file upload example

In this post, I am going to explain how to upload a file using Jersey. Following is the step-by-step procedure to develop complete application.

Step 1: Create a dynamic web project in Eclipse.

File -> New -> Dynamic Web Project

Give the project name as ‘jersey_fileupload’.Press Next. Select the checkbox ‘Generate web.xml deployment descriptor’.


Step 2: Convert ‘jersey_fileupload’ to maven.
Rightclick on the project -> Configure -> Convert to Maven project
Following is the project structure.


Step 3: Update web.xml like below.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 <display-name>jersey_fileupload</display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
  <servlet-name>Jersey REST Service</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.jersey_fileupload</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 REST Service</servlet-name>
  <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>

</web-app>

Following statements instruct Jersey to scan the package(com.jersey_tutorial) and register any found resources and providers automatically.

<init-param>
         <param-name>jersey.config.server.provider.packages</param-name>
         <param-value>com.jersey_fileupload</param-value>
</init-param>

If you want to add multiple package, add them as comma separated.

<init-param>
         <param-name>jersey.config.server.provider.packages</param-name>
         <param-value>com.jersey_fileupload, com.example</param-value>
</init-param>


Step 4: Update pom.xml for maven dependencies.

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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>jersey_fileupload</groupId>
 <artifactId>jersey_fileupload</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>
 <build>
  <sourceDirectory>src</sourceDirectory>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
   <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
     <warSourceDirectory>WebContent</warSourceDirectory>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>
  </plugins>
 </build>

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

  <dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.21</version>
  </dependency>

  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

 </dependencies>
</project>


Step 5: Create new jsp page ‘form.jsp’.

Right click on project -> New -> JSP File.

form.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Page</title>
</head>
<body>
 <h1>Upload a File</h1>

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

  <p>
   Select a file : <input type="file" name="file" size="50" />
  </p>

  <input type="submit" value="Upload" />
 </form>

</body>
</html>


Step 6: Create a package ‘com.jersey_fileupload’ and define class FileUpload.java.

package com.jersey_fileupload;

import java.io.File;
import java.io.InputStream;

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.apache.commons.io.FileUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/files")
public class FileUpload {
 private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/Users/harikrishna_gurram/";

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

  String filePath = SERVER_UPLOAD_LOCATION_FOLDER
    + contentDispositionHeader.getFileName();

  saveFile(fileInputStream, filePath);

  String output = "File saved to server location : " + filePath;

  return Response.status(200).entity(output).build();

 }

 private void saveFile(InputStream inputStream, String destination) {
  try {
   FileUtils.copyInputStreamToFile(inputStream, new File(destination));
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }

 }

}


Complete project structure looks like below.


Run the application on server and hit following URL.


Browse the file and submit.

You will get following kind of output.






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment