AJAX File Upload Progress for Java

AJAX File Upload Progress for Java Using Commons and XML

Most of the browser-based applications created today seem to have one thing in common: AJAX. AJAX stands for Asynchronous JavaScript and XML. It does not matter what language the page is written in. It can be PHP, JSP, ASP, or simply straight HTML. Either way, AJAX will give your web page that “Fat Client” feel that previous browser-based applications could not achieve.

This article will cover how to upload a file to your web server using the Apache Commons FileUpload package as well as how to add AJAX to the page to give the user immediate feedback as to how their upload is doing.

Figure 1: File uploading to server

Figure 2: File finished uploading

To get started, you can create a basic skeleton version of your Servlet.

package com.psclistens.ajax.fileupload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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;

 * This is a File Upload Servlet that is used with AJAX
 * to monitor the progress of the uploaded file. It will
 * return an XML object containing the meta information
 * as well as the percent complete.
public class FileUploadServlet
   extends HttpServlet
   implements Servlet
   private static final long serialVersionUID = 2740693677625051632L;

   public FileUploadServlet()

   protected void doGet(HttpServletRequest request,
                        HttpServletResponse response)
      throws ServletException, IOException

   protected void doPost(HttpServletRequest request,
                         HttpServletResponse response)
      throws ServletException, IOException

Now that the skeleton Servlet is complete, create your web.xml file and add your new Servlet to it.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"

      <description>Servlet for file uploads</description>
      <display-name>File Upload Servlet</display-name>



Next, you need to create a class that implements ProgressListener. ProgressListener is a class in org.apache.commons.fileupload.

package com.psclistens.ajax.fileupload;

import org.apache.commons.fileupload.ProgressListener;

 * This is a File Upload Listener that is used by Apache
 * Commons File Upload to monitor the progress of the
 * uploaded file.
public class FileUploadListener
   implements ProgressListener
   private volatile long
      bytesRead = 0L,
      contentLength = 0L,
      item = 0L;

    public FileUploadListener()

   public void update(long aBytesRead, long aContentLength,
                      int anItem)
      bytesRead = aBytesRead;
      contentLength = aContentLength;
      item = anItem;

   public long getBytesRead()
      return bytesRead;

   public long getContentLength()
      return contentLength;

   public long getItem()
      return item;

So far, so good. Now, you need to create the doPost() method of your servlet. Add the following code to the method.

   protected void doPost(HttpServletRequest request,
                         HttpServletResponse response)
      throws ServletException, IOException
      // create file upload factory and upload servlet
         factory = new DiskFileItemFactory();
         upload = new ServletFileUpload(factory);

      // set file upload progress listener
         listener = new FileUploadListener();

         session = request.getSession();

      session.setAttribut("LISTENER", listener);

      // upload servlet allows to set upload listener

         uploadedItems = null;
         fileItem = null;
         // Path to store file on local system
         filePath = "c:\\temp";

         // iterate over all uploaded files
         uploadedItems = upload.parseRequest(request);

            i = uploadedItems.iterator();

         while (i.hasNext())
            fileItem = (FileItem) i.next();

            if (fileItem.isFormField() == false)
               if (fileItem.getSize() > 0)
                     uploadedFile = null;
                     myFullFileName = fileItem.getName(),
                     myFileName = "",
                     slashType = (myFullFileName.lastIndexOf("\\")
                        > 0) ? "\\" : "/";    // Windows or UNIX
                     startIndex =

                  // Ignore the path and get the filename
                  myFileName = myFullFileName.substring
                    (startIndex + 1, myFullFileName.length());

                  // Create new File object
                  uploadedFile = new File(filePath, myFileName);

                  // Write the uploaded file to the system
      catch (FileUploadException e)
      catch (Exception e)

More by Author

Must Read