Monday, February 20, 2012

Ajaxifying File Upload with HTML5/Servlet3.0

This post will describe about uploading a file in ajax without any third party java script libraries or tools which are used to upload files in asynchronous way.  


To show case the demo, I have used FormData javascript library as my client side API & Servlet3.0 as my server side component, Eclipse Indigo as IDE and Tomcat 7 as the web container. I have followed bellow steps to do the sample app. 


I have created a Dynamic Web Application with version 3 supported. So that, servlet 3 support will be added. 
Created a jsp file named index.jsp which is main UI page. the code snippet for index.jsp is given below .


Have used simple input type file & a button to upload the selected file. On click of the upload button, I am calling a javascript function startUploading(this). The former method will create a javascript FormData object & send the object in the XHR-Ajax post method. the code snippet for the same function is given  below.



We can notice few javascript built in functions.
First we have created a FormData Object with passing the html form object.  
var vFD = new FormData(document.getElementById('upload_form'));
vFD will hold all the information about the HTML file component.


Again, we have created XMLHttpRequest (V2) Object with method type:POST, the invoking URL as upload & async as true. The URL is nothing but the server side component, to which we will post our FormData Object through ajax. For our case I have used an servlet (v3) as my server side component which will save the received file in the disk or file system. 


Servlet 3 has built in support for handling multipart/form-data. Which means we don't have to depend upon third party libraries like apache commons file upload. Servlet 3 has introduced new interface named as Part which can be retrieved from the HttpServletRequest object. The Part object will hold the file information available in the request. We can retrieve the file content, file length, file type from the Part object. The Part interface has a write method which write the file to a location being passed as a method parameter. Please see the code below.


Part p = request.getPart("image_file"); 
This will create a object of Part from the request object.
p.write(disk_path);
This will write the file to the disk path specified in the method.


The code snippet for the above servlet (UploadServlet) is given below




Working demo of this application can be found out here.

















1 comment: