Saturday, April 28, 2012

Servlet File Upload Example

Java Servlet file upload example
This Servlet File Upload tutorial explains how to handle the file upload in Servlets.
This tutorial explains
  1. Handling file upload using apache commons-file file upload API.
File upload specification is contained in RFC 1867 ‘form based file upload in HTML’.
Note: Servlet 3.0 Specification has built in file upload support. With servlet 3.0, you don't need to use any external library like commons file upload. Read this @MultipartConfig : Servlet 3.0 File Upload Example For more details on built in file upload support in servlet 3.0 specification.

Handling file upload using commons file upload API

The commons File Upload package makes it easy to add robust, high performance, file upload capacity to your Servlets and web applications.

Download and install Commons File Upload package

First of all, download the latest version of commons file upload package from here. FileUpload depends on Commons IO package, so download the version mentioned on the FileUpload dependency page. t the time of writing this tutorial, the latest version of Commons File Upload is 1.2.1 which depends on Commons IO version 1.3.2. Installation is very easy. Extract both of the downloaded zip files and put commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar jar files into the WEB-INF/lib folded of your web application.
The next step is to create the HTML file.

Create the HTML file with file input field

It is very easy to write the HTML file that supports file upload.
  1. Set the content type of the HTML form to multipart/form-data.
  2. Add the file input type filed into the HTML form.
As specified in RFC1867, to support the file upload, Content type of the POST request must be set to multipart/form-data. This can be done by setting the value of ENCTYPE attribute of HTML form to multipart/form-data
<form action=”/FileUploadServlet” ENCTYPE=”mulipart/form-data” method=”POST”>
File input type field displays a file input box which allows user to select a file to upload.
<input type=”file” name=”file”/>
There can be any number of file input fields in a HTML form.
Copy the following code into upload.html file. Save the file directly under the web application root directory
<html>
 <head></head>
 <body>
  <p>Commons File Upload Example</p>
  <form action="Commonsfileuploadservlet" enctype="multipart/form-data" method="POST">
   <input type="file" name="file1"><br>
   <input type="Submit" value="Upload File"><br>
  </form>
 </body>
</html>

The File Upload Servlet

Copy the following code into CommonsFileUploadServlet.java.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
 
public class CommonsFileUploadServlet extends HttpServlet {
 private static final String TMP_DIR_PATH = "c:\\tmp";
 private File tmpDir;
 private static final String DESTINATION_DIR_PATH ="/files";
 private File destinationDir;
 
 public void init(ServletConfig config) throws ServletException {
  super.init(config);
  tmpDir = new File(TMP_DIR_PATH);
  if(!tmpDir.isDirectory()) {
   throw new ServletException(TMP_DIR_PATH + " is not a directory");
  }
  String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
  destinationDir = new File(realPath);
  if(!destinationDir.isDirectory()) {
   throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
  }
 
 }
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     PrintWriter out = response.getWriter();
     response.setContentType("text/plain");
     out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
     out.println();
 
  DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
  /*
   *Set the size threshold, above which content will be stored on disk.
   */
  fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
  /*
   * Set the temporary directory to store the uploaded files of size above threshold.
   */
  fileItemFactory.setRepository(tmpDir);
 
  ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
  try {
   /*
    * Parse the request
    */
   List items = uploadHandler.parseRequest(request);
   Iterator itr = items.iterator();
   while(itr.hasNext()) {
    FileItem item = (FileItem) itr.next();
    /*
     * Handle Form Fields.
     */
    if(item.isFormField()) {
     out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
    } else {
     //Handle Uploaded files.
     out.println("Field Name = "+item.getFieldName()+
      ", File Name = "+item.getName()+
      ", Content type = "+item.getContentType()+
      ", File Size = "+item.getSize());
     /*
      * Write file to the ultimate location.
      */
     File file = new File(destinationDir,item.getName());
     item.write(file);
    }
    out.close();
   }
  }catch(FileUploadException ex) {
   log("Error encountered while parsing the request",ex);
  } catch(Exception ex) {
   log("Error encountered while uploading file",ex);
  }
 
 }
 
}
Compile the CommnonsFileUploadServlet.java file as explained in tutorial Servlet Example and put the class file inside WEB-INF/classes directory.

Web.xml servlet mapping

 <servlet>
  <servlet-name>CommonsFileUploadServlet</servlet-name>
  <servlet-class>CommonsFileUploadServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>CommonsFileUploadServlet</servlet-name>
  <url-pattern>/Commonsfileuploadservlet</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>/upload.html</welcome-file>
 </welcome-file-list> 
Create two folders tmp and files under your web application root directory. deploy the application to tomcat server and start the server.
Access the application in browser and upload any file. The file would be uploaded to server and saved under the files directory of the application.

Resources

Other useful resources on Servlet file upload.
  1. Apache commons file upload API
  2. HttpClient and File Upload

1 comment: