About Me

My photo
India
Hey there, lovely people! I'm Hemant Menaria, and I'm passionate about programming. Having completed my MCA in 2011, I've delved into the world of coding with fervor. I believe in sharing knowledge, making complex concepts easy to grasp for everyone. JAVA, PHP, and ANDROID hold a special place in my heart, and I spend most of my time immersed in them. Currently, I'm deeply engaged in API/Webservice frameworks and crafting Hybrid mobile applications to enhance flexibility in the digital realm. If you ever find yourself stuck with a programming challenge, feel free to reach out to me at +91-8955499900 or drop me a line at hemantmenaria008@gmail.com. I'm always eager to help fellow enthusiasts navigate the intricacies of coding!

Monday, May 12, 2014

File upload in java web through ajax Asynchronous



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,

01<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
02    pageEncoding="ISO-8859-1"%>
03http://www.w3.org/TR/html4/loose.dtd
">
04<html>
05<head>
06<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
07<title>Asynchronous file Upload in Java Web Application</title>
08<script src="jquery-1.8.2.js"></script>
09<script src="jquery.ajaxfileupload.js"></script>
10<script language="Javascript">
11$(document).ready(function(){
12  $('input[type="file"]').ajaxfileupload({
13       'action': 'UploadFile',           
14   'onComplete': function(response) {        
15         $('#upload').hide();
16         alert("File SAVED!!");
17       },
18       'onStart': function() {
19         $('#upload').show();
20       }
21  });
22});
23</script>
24</head>
25<body>
26<form>
27<div>                                
28 <input type="file" name="datafile" />  
29 
30 <div id="upload" style="display:none;">Uploading..</div>
31</div>
32</form>
33</body>
34</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.

01import java.io.IOException;
02import javax.servlet.ServletException;
03import javax.servlet.annotation.WebServlet;
04import javax.servlet.http.HttpServlet;
05import javax.servlet.http.HttpServletRequest;
06import javax.servlet.http.HttpServletResponse;
07 
08import java.io.File;
09import java.util.Iterator;
10import java.util.List;
11 
12import org.apache.commons.fileupload.FileItem;
13import org.apache.commons.fileupload.FileItemFactory;
14import org.apache.commons.fileupload.FileUploadException;
15import org.apache.commons.fileupload.disk.DiskFileItemFactory;
16import org.apache.commons.fileupload.servlet.ServletFileUpload;
17/**
18 * Servlet implementation class UploadFile
19 */
20@WebServlet("/UploadFile")
21public class UploadFile extends HttpServlet {
22 private static final long serialVersionUID = 1L;
23 
24    /**
25     * Default constructor.
26     */
27    public UploadFile() {
28        // TODO Auto-generated constructor stub
29    }
30 
31 /**
32  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
33  */
34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35  // TODO Auto-generated method stub
36 }
37 
38 /**
39  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
40  */
41 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
42    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
43     
44         if (isMultipart) {
45          // Create a factory for disk-based file items
46          FileItemFactory factory = new DiskFileItemFactory();
47 
48          // Create a new file upload handler
49          ServletFileUpload upload = new ServletFileUpload(factory);
50   
51             try {
52              // Parse the request
53     List /* FileItem */ items = upload.parseRequest(request);
54     Iterator iterator = items.iterator();
55                 while (iterator.hasNext()) {
56                     FileItem item = (FileItem) iterator.next();
57                     if (!item.isFormField()) {
58                         String fileName = item.getName(); 
59                         String root = getServletContext().getRealPath("/");
60                         File path = new File(root + "/uploads");
61                         if (!path.exists()) {
62        boolean status = path.mkdirs();
63                         }
64   
65                         File uploadedFile = new File(path + "/" + fileName);
66                         System.out.println(uploadedFile.getAbsolutePath());
67                         item.write(uploadedFile);
68                     }
69                 }
70             } catch (FileUploadException e) {
71                 e.printStackTrace();
72             } catch (Exception e) {
73                 e.printStackTrace();
74             }
75         }
76 }
77 
78}
4. Now the last step is to map the servlet to the action url we have used in index.jsp file as shown below,
01<web-app>
02  <display-name>AjaxFileUpload</display-name>
03  <servlet>
04  <servlet-name>UploadFile</servlet-name>
05  <servlet-class>com.programmingfree.fileupload</servlet-class>
06 </servlet>
07 <servlet-mapping>
08  <servlet-name>UploadFile</servlet-name>
09  <url-pattern>/UploadFile</url-pattern>
10 </servlet-mapping>
11</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,

No comments:

Post a Comment