Asynchronous (AJAX Style) File Upload in Java Web Application

DOWNLOAD File upload process involves data to be sent from client side to server, in html terms this means submitting form to ser...




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"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<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">
$(document).ready(function(){ 
  $('input[type="file"]').ajaxfileupload({
       'action': 'UploadFile',            
   'onComplete': function(response) {         
         $('#upload').hide();
         alert("File SAVED!!");
       },
       'onStart': function() {
         $('#upload').show(); 
       }
  });
});
</script>
</head>
<body>
<form>
<div>                                 
 <input type="file" name="datafile" />   <br/>
 <div id="upload" style="display:none;">Uploading..</div>
</div>
</form>
</body>
</html>

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 java.io.IOException;
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.io.File;
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
 */
@WebServlet("/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) iterator.next();
                     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);
                         System.out.println(uploadedFile.getAbsolutePath());
                         item.write(uploadedFile);
                     }
                 }
             } catch (FileUploadException e) {
                 e.printStackTrace();
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
 }

}

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

<web-app>
  <display-name>AjaxFileUpload</display-name>
  <servlet>
  <servlet-name>UploadFile</servlet-name>
  <servlet-class>com.programmingfree.fileupload</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>UploadFile</servlet-name>
  <url-pattern>/UploadFile</url-pattern>
 </servlet-mapping>
</web-app>

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!!

Subscribe to GET LATEST ARTICLES!


Related

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(WebappClassLoader.java:1714)
    ....
    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.

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

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

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

    ReplyDelete
  4. hi,
    it can only transfer jpg files?

    ReplyDelete
  5. hi,
    it can only transfer jpg files?

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

    ReplyDelete
  7. hey dude,

    work with struts 1?

    ReplyDelete
  8. Very useful. Thanks a lot.

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

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

    where is download?

    thank you

    ReplyDelete
  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

    ReplyDelete
  12. is it com.programmingfree.fileupload or UploadFile. It showing file saved but i'm not able to debug or print sys logs to see where they got saved

    ReplyDelete
  13. Uncaught TypeError: $(...).ajaxFileUpload is not a function. Please help.

    ReplyDelete
    Replies
    1. It seems like you haven't add properly jquery.ajaxfileupload.js into your app. Make sure of path and wether jQuery is being loaded or not.

      Delete
  14. hi..
    Thanks for the tutorial.
    Can you please explain where is the location of saved file?

    ReplyDelete
  15. hi..
    Thanks for the tutorial.
    Can you please explain where is the location of saved file?

    ReplyDelete
  16. It is only working for Images I want it to work for other type of files also what I have to do?

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

      Delete
  17. In jquery.ajaxfileupload.js add/change the extension in valid_extensions array.

    ReplyDelete
  18. valid_extensions : ['gif','png','jpg','jpeg','doc', 'txt','pdf']...awesome initially was not aware about how its working but once seen comments everything then works fluently ...Zhakkas!!!

    ReplyDelete
  19. Furthermore, there are lots of technological words, words with several definitions, and also colloquial expressions that cannot be equated straight that can be troublesome. Locqa is the best system to translate or localize anything.

    ReplyDelete
  20. great blog before reding this blog I was concerned with University Assignment Writing Services for making my assignments of the java web but after reading this I got so many things.

    ReplyDelete
  21. one that is under the protection of another : dependent a first-rate power, able to defend her political clients in central and leather jacket website eastern Europe— W. W. Kulski. 2a : a person who engages the professional advice or services of another a lawyer's clients a personal trainer.

    ReplyDelete
  22. Awesome post! Really enjoyed this post. But I want more information on such valuable topic. Excellent posts to read keep it up and keep going on this way. And keep sharing these types of things Thanks startup tips

    ReplyDelete
  23. Your greatest choice is to hasten CEMENT TREATED BASE services in Austin Contracts! Because of the meticulousness CEMENT TREATED BASEof our talented team of contractors, the process will go smoothly from beginning to conclusion.

    ReplyDelete
  24. The Java Web Application is a great way to learn how to create web applications. It is very user-friendly and easy to use. I would recommend this to anyone who wants to learn how to create a web application. The team here is knowledgeable and experienced, and they're always willing to help. They'll make sure you understand the material and get the best management assignment help with good grades possible.

    ReplyDelete
  25. you will feel the rush of triumph as you Valorant Dubaicompete against your opponents.

    ReplyDelete
  26. Since we recognize that the valueWorking Capital in Dubai of your error above all other considerations, we have

    ReplyDelete
  27. Best interior design in Bangladesh https://limrs.com/interior-design-in-bangladesh/

    ReplyDelete
  28. Certainly! However, I'll need more specific information about the blog you'd like to comment on. Please provide the title or topic of the blog, and I can help you craft a relevant and engaging comment.
    msradix.

    ReplyDelete
  29. Navigate the complex world of logistics with confidence by delving into the intricacies of a internal audit dashboard. In this comprehensive guide, we demystify the process, offering invaluable insights into how businesses can enhance their supply chain operations.

    ReplyDelete
  30. The detailed steps on setting up the server-side with Java Servlet and handling the client-side with JavaScript are very clear and practical. https://hexacorp.com/improving-infrastructure-performance-with-the-cloud

    ReplyDelete
  31. Taking time to explore and unwind can spark new creativity and ideas. For top-tier design inspiration, look into top interior fit out companies in Dubai.







    ReplyDelete
  32. Prem Green offers the best organic mehendi, made from 100% natural, chemical-free henna. This premium product provides a rich, long-lasting stain while nourishing the skin. Perfect for both hair and body art, Prem Green ensures a safe and vibrant mehendi experience with every application, free from harmful chemicals.

    https://www.premgreen.com/organic-mehndi-for-hair/

    ReplyDelete

emo-but-icon

SUBSCRIBE


item