Jquery Ajax upload with Progress bar – Spring Framework

I posted about how to limit the file size while uploading it recently. File upload can be a time taking process in following two cases:

a. You are uploading a large file
b. Your connection speed is slow

In both cases it is good to show progress of file upload to the user as it shows him exactly how much to wait before proceeding to next action. Using the same set of files at back-end (if your are using Spring framework) we can show the progress of file upload.

I did this using following things:

1. JQuery
2. ajaxfileupload plugin of JQuery
3. jQuery Progress bar plugin
4. Some changes/additions in the code which was posted in my previous post.

Step 1: Write a controller which will return the upload progress information to HTML page so that Page javascript can show progress bar accordingly. In the previous post i have given code for AjaxProgressListener which sets the file upload progress information in session object. This Controller will use the session object to get progress information and return it to page.

 
package com.controllers;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import net.sf.json.JSONObject;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
 
public class UploadInfoController extends AbstractCommandController {
	private final static Log logger = LogFactory.getLog(UploadInfoController.class);
    public UploadInfoController() {
        setCommandClass(Object.class);
    }
 
	@Override
	protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		JSONObject jsonResp = new JSONObject();
		try {
			HttpSession session = request.getSession();
			jsonResp.put("progressMap", session.getAttribute("progressMap"));
			jsonResp.put("result", session.getAttribute("progressStatus"));
		} catch (Exception e) {
			logger.error(e);
			jsonResp.put("result", "error");
		} finally {
			response.getWriter().print(jsonResp);
            response.flushBuffer();
		}
		return null;
	}
}
 
 

Needless to say that entry of this controller will be required in your-app.xml as bean and then as url mappings section so that HTML page can access this controller using the mapping path.

Step 2 : While uploading file using ajaxfile upload also use the jquery progress bar plugin. I used it in following way:

 
function showUploadProgress() {
	$("#upload_bar").show();
	$("#upload_bar").progressBar({barImage: '../images/progressbg_green.gif', boxImage: '../images/progressbar.gif', width:300, height:17});
	var uploadInfo = function getUploadInfo() {
		$.ajax({
			url: '../portal/uploadInfo',
			type: "POST",
			cache: false,
			dataType: "json",
			async: false,
			success: function(msg){
				if(msg.result == 'UPLOADING') {
					var progressMap = msg.progressMap;
					var progressVal = (progressMap.bytesRead/progressMap.contentLength) * 100;
					$("#upload_bar").progressBar(progressVal);
				} else if(msg.result == 'DONE') {
					$("#upload_bar").hide();
					clearInterval(uploadInfoHandle);
				} else if(msg.result == 'MAX_SIZE_EXCEEDS') {
					clearInterval(uploadInfoHandle);
					$("#upload_bar").hide();
					showErrorMsg(getI18N("importleads.upload_10mb"));
				} else {
					clearInterval(uploadInfoHandle);
					showErrorMsg(msg);
				}
			},
			error: function(msg){
				clearInterval(uploadInfoHandle);
				showErrorMsg(getI18N("importleads.unknown_error"));
			}
		});
	};
	var uploadInfoHandle = setInterval(uploadInfo, 2000);
}
 

Use the function above while uploading your file using ajaxfileupload plugin.

 
function ajaxFileUpload() {
	showUploadProgress();
	$.ajaxFileUpload({
		url:serverurl,
		secureuri:false,
		fileElementId:'file',
		dataType: 'json',
		success: function (data) {
			if (data.result == 'success') {
				//Show Success
			}
			if(data.result == 'error') {
				//Show error
			}
 
		},
		error: function (data) {
			//Show error
		}
	});
}
 

Most Commented Posts

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

what is the use of Json? why we use jason? and where exactly we need this & what is the adv to use this?

can u give download project example?
please send to my email.
Thanks..

Hi, Nice example. I have a suggestion regarding the controller use you can use spring 3 annotation controller this will simplify lots of work.

I humbly request to update with the project download link or cld u please mail me.

Thank you

hi…
im not understand this logic
can u give download project example?
please send to my email.

canu pls help me with multiple uploads with json_+jquerry
]

hello,
this solution doesn’t work. i don’t get the status continuous back from the server.
can you please send me a project example to my email?
that would be very nice. i need that so much.

thank you and regards,
donny

I am not able to get this to work. I do not understand how the update method is called.

Hi,
I do not understand your logic is that you can send me the example of the project in zip

thanks

Jilane

Leave a comment

(required)

(required)