Asynchronous (AJAX Style) File Upload in Java Web Application

File upload process involves data to be sent from client side to server, in html terms this means submitting form to server side method that gets the file from request object and saves it to the server. Most of the time, it is desirable to implement file upload in ajax way without refreshing the whole page while updating the user on the progress.

It is a known fact that, it is not possible to do AJAX file uploads to server using $.ajax or XMLHttpRequest since jquery or javascript does not support file uploads for security reasons. We are now left out with two options/workarounds, to use flash or to use hidden iframe. Flash depends on a plugin to be installed on the user's browser which some people ans companies don't allow. So, out of the two options, the best option is to go for hidden iframe solution. This blog post contains an excellent article on how to do this with plain javascript.

To make the job more easier, let us use this jQuery plugin called jQuery.AjaxFileUpload.js which exactly implements the hidden iframe technique behind the scenes along with progress update and cancelling options. The logic is simple, instead of submitting the form to the server which would cause a postback, we submit the contents of the form to an iframe that is created dynamically and let the iframe communicate with the server, once the upload is complete - iframe sends the response back to the form. Steve explains this technique here in a very neat manner, so I don't want to repeat this here again.

To handle file upload in the server side, let us use Apache Commons File Upload library that makes the job very simple and easy.

1. Download all the required scripts and libraries,

2. Create a dynamic web project in Eclipse. Add the jar files to WEB-INF/lib directory and script files to WebContent folder.

2. Create a jsp file in WebContent and copy paste the below code,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Asynchronous file Upload in Java Web Application</title>
<script src="jquery-1.8.2.js"></script>
<script src="jquery.ajaxfileupload.js"></script>
<script language="Javascript">
       'action': 'UploadFile',            
   'onComplete': function(response) {         
         alert("File SAVED!!");
       'onStart': function() {
 <input type="file" name="datafile" />   <br/>
 <div id="upload" style="display:none;">Uploading..</div>

Note that I have referenced jquery files in the head section of the html. The execution of script is very simple, whenever a file is selected using the file browse input, the script gets fired and submits the selected file to the servlet called 'UploadFile'. The action parameter takes the servlet url which handles the file upload logic in the server side. The onStart and onComplete methods are fired while the file starts to upload and after successful completion of file upload. I have used these methods to show file upload progress to the user.

3. Now let us use Apache Commons Fileupload library to handle file upload in the server side. Create a servlet and place the below code in it.

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Iterator;
import java.util.List;

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;
 * Servlet implementation class UploadFile
public class UploadFile extends HttpServlet {
 private static final long serialVersionUID = 1L;

     * Default constructor. 
    public UploadFile() {
        // TODO Auto-generated constructor stub

  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub

  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
         if (isMultipart) {
          // Create a factory for disk-based file items
          FileItemFactory factory = new DiskFileItemFactory();

          // Create a new file upload handler
          ServletFileUpload upload = new ServletFileUpload(factory);
             try {
              // Parse the request
     List /* FileItem */ items = upload.parseRequest(request);
     Iterator iterator = items.iterator();
                 while (iterator.hasNext()) {
                     FileItem item = (FileItem);
                     if (!item.isFormField()) {
                         String fileName = item.getName();  
                         String root = getServletContext().getRealPath("/");
                         File path = new File(root + "/uploads");
                         if (!path.exists()) {
        boolean status = path.mkdirs();
                         File uploadedFile = new File(path + "/" + fileName);
             } catch (FileUploadException e) {
             } catch (Exception e) {


4. Now the last step is to map the servlet to the action url we have used in index.jsp file as shown below,


That is all! Now run the application in Tomcat server and upload a file to see how it gets uploaded without refreshing the whole page.

Once the file is uploaded,

Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!



Jquery 812963292810332364

Post a Comment

  1. Hi, nice tutorial.
    However while running it I am getting
    java.lang.ClassNotFoundException: com.fileuploadpoc.UploadFile
    at org.apache.catalina.loader.WebappClassLoader.loadClass(
    by the way in the screen shot (point-2) you show that you have added commons-fileupload-1.3-java in the lib. Is it really required? I am asking as commons-fileupload-1.3.jar is already there in the lib folder.

    1. Change the web.xml to com.programmingfree.fileupload.UploadFile

  2. Its NOt Working , I tried To put Log statements into Servlets & Alert Boxes into Javascript but they are not getting called ....

  3. how does this work in multipart/form-data form?
    your example works...but in another form i can do it to work...

  4. hi,
    it can only transfer jpg files?

  5. hi,
    it can only transfer jpg files?

  6. Change valid_extensions : ['gif','png','jpg','jpeg'] in jquery.ajaxfileupload.js file for custom file type.

  7. hey dude,

    work with struts 1?

  8. Very useful. Thanks a lot.

  9. The dropbox link to download is broken (404) :-(
    Can you please fix, thanks

  10. i want file name
    import java.util.Iterator;
    import java.util.List;

    where is download?

    thank you

  11. when I am executing your program in Internet Explorer, I am getting access denied error. I tried by upgrading jquery latest version/ commenting error code etc. after that I am getting doc type error in the html page any suggestion please





Currency Converter

Built using AngularJS and ASP.NET Web API