easy, elegant and effective code…

This sample code will help you to understand how you can upload multiple files by using the RESTful Web Service. Here I have used Apache’s Common Fileupload (ACF) API for uploading multiple files.  ACF parses HTTP requests which conform to RFC 1867, “Form-based File Upload in HTML”. That is, if an HTTP request is submitted using the POST method, and with a content type of “multipart/form-data”, then ACF can parse that request, and make the results available in a manner easily used by the caller.

Server Side Code –

package com.crispCode.rest;

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 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 RESTMultipleFileUpload
{
    private static final String FILE_UPLOAD_PATH = "C:/WINDOWS/Temp";
    private static final String CANDIDATE_NAME = "candidateName";
    private static final String SUCCESS_RESPONSE = "Successful";
    private static final String FAILED_RESPONSE = "Failed";
    
    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces("text/plain")
    @Path("/multipleFiles")
    public String registerWebService(@Context HttpServletRequest request)
    {
        String responseStatus = SUCCESS_RESPONSE;        
        String candidateName = null;
        
        //checks whether there is a file upload request or not
        if (ServletFileUpload.isMultipartContent(request))
        {
            final FileItemFactory factory = new DiskFileItemFactory();
            final ServletFileUpload fileUpload = new ServletFileUpload(factory);
            try
            {
                /*
                 * parseRequest returns a list of FileItem
                 * but in old (pre-java5) style
                 */
                final List items = fileUpload.parseRequest(request);
                
                if (items != null)
                {
                    final Iterator iter = items.iterator();
                    while (iter.hasNext())
                    {
                        final FileItem item = (FileItem) iter.next();
                        final String itemName = item.getName();
                        final String fieldName = item.getFieldName(); 
                        final String fieldValue = item.getString();

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

                    }
                }
            }
            catch (FileUploadException fue)
            {
                responseStatus = FAILED_RESPONSE;
                fue.printStackTrace();                
            }
            catch (Exception e)
            {
                responseStatus = FAILED_RESPONSE;
                e.printStackTrace();
            }
        }        
        
        System.out.println("Returned Response Status: " + responseStatus);
        
        return responseStatus;
    }
}

Code Description

Line #39: call the isMultipartContent() method of class ServletFileUpload which takes one parameter request. This method checks whether there is a file upload request or not. It returns a boolean value.

Line #41: If there is a request for uploading a file then create an object of DiskFileItemFactory class which implements FileItemFactory. The implementation of FileItemFactory means that it creates FileItem instances which keep their content either in memory or disk. While using the DiskFileItemFactory the temporary files are automatically deleted as soon as they are no longer needed. The interface FileItemFactoryis a factory for creating FileItem instances.

Line #42: Passing the object of FileItemFactory which has the reference of class DiskFileItemFactory inside the constructor of class ServletFileUpload(). This is used to constructs an instance of this class which uses the supplied factory to create FileItem instances.

Line #49: Calling the method parseRequest(), passing the request object which returns a list of FileItem instances parsed from the request, in the order they were transmitted.

Line #57: When the item if a file, item.getName() will return the file name otherwise null will be returned.

Line #61: FileItem, this interface represents a file or form item received within a multipart/form-data POST request. Checking if the item is Form field or File.

Line #69-72: if the item is file, save the file to disc using FileItem’s write() method, passing the instance of File object.

Line #92: Returning the response status. In case of any exception, ‘Failure’ response will be returned otherwise ‘Successful’ response will be returned.

Client Side (JSP) Code to Upload Multiple Files

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

Deployment descriptor File –

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>RESTMultipleFileUpload</display-name>
	<servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
		<init-param>
			<param-name>com.sun.jersey.config.property.packages</param-name>
			<param-value>com.crispCode.rest</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>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

Description of the deployment descriptor for registering the Jersey as the servlet dispatcher, refer my earlier post.

Required Jar Files

Following is the list of jar files required for successful development and deployment –

  • asm-3.3.1.jar
  • commons-codec-1.3.jar
  • commons-fileupload-1.2.1.jar
  • commons-io-1.3.2.jar
  • commons-logging-1.1.1.jar
  • jersey-bundle-1.12.jar
  • jersey-core-1.12.jar

References

http://commons.apache.org/
http://jersey.java.net/nonav/documentation/latest/index.html

Advertisements

Comments on: "Jersey REST Web Service to Upload Multiple Files" (2)

  1. Many thanks for this solution!
    Helped me a lot!
    Márcio
    Brazil
    South America

  2. Awesome. Very helpful to solve my problem..

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: