Tracking file upload progress only using jQuery

Tracking file upload progress only using jQuery

4 min. read

Snapshots of the application

1. File upload interface

File upload interface

2. File selection

File selection

3. File upload in progress

File upload in progress

4. File upload completed

File upload completed

Creating directories( folders ) for the application

  1. Create a directory named myWebApp in your server root directory eg. in www directory (for windows).
  2. Create 3 subdirectories named css, js and myServer inside your myWebApp directory.
  3. Create a subdirectory named uploads inside your myServer directory, uploaded images will be stored here.

HTML markup

<!DOCTYPE html>
<html>
	<head>
		<title>Tracking file upload progress only using jQuery</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
		<link rel="stylesheet" href="css/my_styles.css">
	</head>
	<body>
		<div id="progressBar"></div>
		<form>
			<div id="label">Select a file to upload</div>
			<input type="file" name="ufile" required="required">
			<input type="submit" value="Upload file">
		</form>
		<script src="js/uploader.js"></script>
	</body>
</html>

Save this html as main.html file in myWebApp directory.

CSS rules

body
{
	margin:0px;
	font-size:14px;
	font-family:Helvetica,arial,sans-serif;
}

#progressBar
{
	width:0px;
	height:5px;
	background-color:#F44336;
	position:fixed;
	top:0px;
	left:0px;
	display:none;
}

#progressBar.active
{
	display:block;
	transition: 3s linear width;
	-webkit-transition: 3s linear width;
	-moz-transition: 3s linear width;
	-o-transition: 3s linear width;
	-ms-transition: 3s linear width;
}

form
{
	width:300px;
	padding:20px;
	margin:100px auto 0 auto;
	border:1px solid #cf2c20;
}

#label
{
	font-size:20px;
	font-weight:bold;
	margin-bottom:20px;
}

input[type="submit"]
{
	display:block;
	width:100%;
	margin-top:20px;
	border-width:0px;
	padding:10px;
	color:#fff;
	background-color:#cf2c20;
	outline:none;
	cursor:pointer;
}

Save this css as my_styles.css file in css directory.

Javascript code

$(function()
{	
	var pbar = $('#progressBar'), currentProgress = 0;
	function trackUploadProgress(e)
	{
		if(e.lengthComputable)
		{
			currentProgress = (e.loaded / e.total) * 100; // Amount uploaded in percent
			$(pbar).width(currentProgress+'%');

			if( currentProgress == 100 )
			console.log('Progress : 100%');
		}
	}

	function uploadFile()
	{
		var formdata = new FormData($('form')[0]);
		$.ajax(
		{
			url:'myServer/uploadHandler.php',
			type:'post',
			data:formdata,
			xhr: function()
			{
				// Custom XMLHttpRequest
				var appXhr = $.ajaxSettings.xhr();

				// Check if upload property exists, if "yes" then upload progress can be tracked otherwise "not"
				if(appXhr.upload)
				{
					// Attach a function to handle the progress of the upload
					appXhr.upload.addEventListener('progress',trackUploadProgress, false);
				}
				return appXhr;
			},
			success:function(){ console.log('File uploaded !'); },
			error:function(){ console.log('Error !'); },

			// Tell jQuery "Hey! don't worry about content-type and don't process the data"
			// These two settings are essential for the application
			contentType:false,
			processData: false 
		})
	}

	$('form').submit(function(e)
	{
		e.preventDefault();
		$(pbar).width(0).addClass('active');
		uploadFile();
	});
})

Save this javascript code as uploader.js file in js directory.

PHP code for handling file upload

<?php
	// PHP script for file upload
	// Note : In production applications you must validate user data.

	$image = $_FILES['ufile'];

	// Get file extension
	$extension = .pathinfo($image['name'],PATHINFO_EXTENSION);

	// Generate random file name
	$fileName = SHA1(time());

	// Path to save the uploaded files
	$path = 'uploads'.DIRECTORY_SEPARATOR.$fileName.$extension;

	// Move the uploaded file to the "uploads" directory
	move_uploaded_file($image['tmp_name'],$path);
?>

Save this php code as uploadHandler.php file in myServer directory.

Note :

When you will run the above application in your browser ( locally ), selected file will be uploaded in a moment and you will see

  1. Progress : 100%
  2. File uploaded !

in the browser console immediately !, but the progress bar still increasing ( what is happening? ) this is because of css transition code of progress bar ( see the css code for progress bar ).

If transition is not applied on progress bar it's width will increase to 100% instantly on file upload, as application is running in your computer locally, to give you the idea of how the application will work in online environment transition is used.

In online environment you will have to remove the css transition code from the css file to track the realtime accurate upload progress.

Write comments