Tuesday 22 September 2015

Jersey 2 upload multiple files

In previous post, I explained how to send an image to client. In this post, I am going to explain how to upload multiple files using Jersey. For this application, I am going to use Apache commons-fileupload library.

Folowing is the step-by-step procedure to develop complete application in eclipse.

Step 1: Create a dynamic web project ‘jersey_fileupload’ in eclipse.
File -> New -> Dynamic Web Project

Give project name as ‘jersey_fileupload’, press Next.

Select the check box ‘Generate web.xml deployment descriptor’ and press Finish.


Step 2: Convert this project to maven project.
Right click on the project -> Configure -> Convert To Maven Project.

Total project structure looks like below.


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.self_learn</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>

Step 4: Update pom.xml like below.

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.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.21</version>
  </dependency>

  <dependency>
   <groupId>org.glassfish.jersey.core</groupId>
   <artifactId>jersey-server</artifactId>
   <version>2.21</version>
  </dependency>

  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>
  
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>


 </dependencies>
</project>


Step 5: Create package ‘com.self_learn’. Define class FileUpload.java.

package com.self_learn;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

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

 @POST
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 @Produces("text/plain")
 @Path("/multipleFiles")
 public Response registerWebService(@Context HttpServletRequest request) {
  String name = null;

  /* Check whether request is multipart or not. */
  if (ServletFileUpload.isMultipartContent(request)) {
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload fileUpload = new ServletFileUpload(factory);
   try {

    List<FileItem> items = fileUpload.parseRequest(request);

    if (items != null) {
     Iterator<FileItem> iter = items.iterator();
     /*
      * Return true if the instance represents a simple form
      * field. Return false if it represents an uploaded file.
      */
     while (iter.hasNext()) {
      final FileItem item = iter.next();
      final String itemName = item.getName();
      final String fieldName = item.getFieldName();
      final String fieldValue = item.getString();

      /* */
      if (item.isFormField()) {
       name = fieldValue;
       System.out.println("Field Name: " + fieldName
         + ", Field Value: " + fieldValue);
       System.out.println("Candidate Name: " + name);
      } else {
       final File file = new File(FILE_UPLOAD_PATH
         + File.separator + itemName);
       System.out.println("Saving the file: "
         + file.getName());
       item.write(file);
      }

     }
    }
   } catch (FileUploadException e) {
    e.printStackTrace();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

  return Response.status(200).entity("Data saved successfully").build();
 }
}


Step 6: Define form.jsp like below.

<html>
<head>
<title>Multiple File Upload Example</title>
</head>
<body>
 <form action="rest/upload/multipleFiles" method="POST"
  enctype="multipart/form-data">
  <div id="fileSection">
   <h1>Multiple File Upload Application</h1>
   <table>
    <tr>
     <td>Name:</td>
     <td><input type="text" name="candidateName" size="45" /></td>
    </tr>
    <tr>
     <td>Resume</td>
     <td><input type="file" name="infoFile" size="45" /></td>
    </tr>
    <tr>
     <td>Photo</td>
     <td><input type="file" name="imgFile" size="45" /></td>
    </tr>
   </table>
  </div>
  <p />
  <input type="submit" value="Upload" />
 </form>
</body>
</html>


Following is the explanation for above program.

ServletFileUpload.isMultipartContent(request)
isMultiPartContent takes HttpServletRequest instance as argument and return true if the request is multipart else false..

List<FileItem> items = fileUpload.parseRequest(request)
A list of FileItem instances parsed from the request, in the order that they were transmitted.

item.isFormField()
Return true if the instance represents a simple form field. Return false if it represents an uploaded file.

Complete project structure looks like below.

Run the application on server and hit following url.

Upload files and submit. They are saved to the location you specified in the constant ‘FILE_UPLOAD_PATH’.





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment