Pages Navigation Menu

Coding is much easier than you think

AJAX File Upload in Java Web Application using jQuery.AjaxFileUpload plugin

 
ajax style file upload in servlet and jsp
 
In my previous article on File Upload Example in Servlet & Jsp we learnt how to upload a file into sever via Apache Commons FileUpload plugin, In this article we shall add ajax style feature to our previous example using jQuery.AjaxFileUpload.js plugin.
 

Modifications

 
Before getting into the tutorial, I will let you know the small modification which I made in jQuery Form Plugin.
 
1. By default this plugin allows only images, this is specified in jQuery.AjaxFileUpload.js as below.

valid_extensions : ['gif','png','jpg','jpeg']

So inorder to upload file with other extensions, I have modified this to

valid_extensions : ['gif','png','jpg','jpeg','txt','docx','pdf','mkv']

You can include/remove these extensions according to your requirement
 
2. When file upload fails this plugin sends two parameter in response, they are
status : Just has the status code, it is set to false when file upload fails
message : This holds the error message.

When file upload is successful, no response is sent back to client. So in order to send an upload success message I have modified the code from

settings.onComplete.apply(element, [response, settings.params]);

to

settings.onComplete.apply(element, [ {
	status : true,
	message : 'Your file has been uploaded!'
}, settings.params ]);

Now let’s go ahead implement ajax file upload functionality in java web application
 

Library

 

Folder structure

 
Now Create a dynamic web project in Eclipse with following folder structure
Ajax file upload
 

JSP

 

<!DOCTYPE html>
<html>
<head>
<title>Asynchronous file Upload in Java Web Application</title>
<script src="jquery-1.8.2.js"></script>
<script src="jQuery.AjaxFileUpload.js"></script>
<script lang="Javascript">
$(document).ready(function() {
  $('input[type="file"]').ajaxfileupload({
  'action' : 'UploadFile',
  'onComplete' : function(response) {
      $('#upload').hide();
      $('#message').show();
			
      var statusVal = JSON.stringify(response.status);

     if(statusVal == "false")
     {
     $("#message").html("<font color='red'>"+JSON.stringify(response.message)+"</font>");
     }	
     if(statusVal == "true")
     {
     $("#message").html("<font color='green'>"+JSON.stringify(response.message)+"</font>");
     }			
},
'onStart' : function() {
	$('#upload').show();
	$('#message').hide();
}
});
});
</script>
<style type="text/css">
.centered {
	width: 100%;
	margin-left: auto;
	margin-right: auto;
	text-align: center;
}
</style>
</head>
<body>
<form>
<div class="centered">
	<h4>AJAX Style File upload in Java Web Application</h4>
	<input type="file" name="file" /><br />
	<div id="upload" style="display: none;">Uploading..</div>
	<div id="message"></div>
</div>
</form>
</body>
</html>

 
The required jquery files are referenced in the head section of jsp file. Here whenever a file is selected, the script gets fired and triggers the servlet via action parameter, which holds the servlet url. This servlet in turn handles the file upload logic in the server side.
 
Another must read:
jQuery form validation using jQuery Validation plugin

jQuery Tutorial for Beginners
 

Servlet

 

package com.fileupload;

import java.io.File;
import java.io.IOException;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String UPLOAD_DIRECTORY = "C:/Files";

	protected void doPost(HttpServletRequest request,
             HttpServletResponse response) throws ServletException, IOException {
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);

	// process only if it is multipart content
	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> multiparts = upload.parseRequest(request);

		for (FileItem item : multiparts) {
		if (!item.isFormField()) {
		String name = new File(item.getName()).getName();
		item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
		}
		}
		} 
		catch (Exception e) 
		{
		  e.printStackTrace();
		}
	}
}
}

 

web.xml

 
Make sure that the web.xml has following mappings

<servlet>
	<servlet-name>UploadFile</servlet-name>
	<servlet-class>com.fileupload.UploadFile</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>UploadFile</servlet-name>
	<url-pattern>/UploadFile</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

 

Demo

 
On Running this application
ajax file upload2
 
When file upload is successful
Ajax file upload6
 
When we try to upload a file whose format is not specified in jQuery.AjaxFileUpload.js file
Ajax file upload4
 
I our next article we shall implement ajax file upload functionality with file upload progress bar.
 
download
 

Reference

 
jQuery.AjaxFileUpload.js
 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • Goutam Sutradhar

    How can i post extra parameter with file in a form?

  • http://gravatar.com/nawazijaz Achilles

    Hi Mohaideen, The response.status is always undefined. Do you know why ? Thank-you.

  • NansJames

    Hi Jamil,I used Jquery for fileupload ( fileupload.js) and the file got uploaded backend am using is struts2. I need to show the thumbnail_url in JSP. Now i got the uploadloaded file name in encrupt format like ( upload_7128fa1b_14a38c275a3__7ffb_00000004.tmp). I don know how to set the url for thumbnail and file ur. Please tell how to handle this struts2. Do i want to set getter/ setter for url in struts2 action? am totally new to jquery.