Upload Progress Bar with jQuery

Another quick post detailing a method for creating an upload progress bar with jQuery for file uploads. More for self reference than anything.

This example is using XHR.upload.onprogress to return a loaded (bytes uploaded) and total (total bytes of the file) value so an upload progress can be computed. We are using the jQuery form plugin for uploading files. We take the “loaded” and “total” values to display and update a progress indicator (status bar and the displayed percentage). Once the AJAX upload has completed, we reset and hide the progress indicator.

Boom.

$(this).ajaxSubmit({
    target: '#output',
	xhr: function()
	{
		myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload)
        {
            $('#progressBar').show();
            myXhr.upload.addEventListener('progress', function(ev){
            	if (ev.lengthComputable) {
	                var percentComplete = Math.round((ev.loaded / ev.total) * 100);
			$('#percentage').text(percentComplete + '%');
			$('#status').css('width', percentComplete+'%');
	        }
            }, false);
            myXhr.upload.addEventListener('load', function(ev){
            	$('#progressBar').hide();
            	$('#percentage').text('0%');
		$('#status').css('width', '0%');
            }, false);
        }
        return myXhr;
	},
	dataType: 'json',
        success:  afterSuccess
});

HTML for the progress indicator:

<div id="progressBar">
	<div id="status"></div>
	<div id="percentage">0%</div>
</div>

CSS for the progress indicator:

#progressBar{
	width: 350px;
	text-align: center;
	height: 16px;
	position: fixed;
	left: 50%;
	margin-left: -175px;
	z-index: 9;
	border:1px solid #9d9d9d;
	border-radius: 5px;
	overflow: hidden;
	top: 45px;
	display: none;
}
#progressBar #status{
	width: 0%;
	background:#00bd67;
	height: 16px;
	transition:1s linear width; /*this gives a smooth effect as the progress increases*/
}
#progressBar #percentage{
	position: absolute;
	text-align: left;
	z-index: 11;
	top: 0;
	left:0;
	font-size: 12px;
	color: #ffffff;
	width: 350px;
	padding-left: 5px;
	line-height: 15px;
}
Upload progress bar with jQuery

Upload progress bar with jQuery

Note: When developing this, I had an issue with the progress being reported waaaaay too fast. On file uploads of ~70Mb the progress would shoot to 100% in a couple of seconds and the upload would churn away in the background until it was complete. I made a post on Stack Overflow and someone suggested that it could be due to antivirus on my machine. I tried on a machine without AV and sure enough it worked great. I’ve tried turning off AV on my work dev machine and it behaved as expected (I’m unsure if it’s anything to do with the brand of anti virus but I have avast on my work machine).

Did you like this post? Why not subscribe?

Leave a Reply

Your email address will not be published. Required fields are marked *