Ajax File Upload with PHP, HTML5 File API and jQuery

Ajax file uploader is useful web tool, which is actually very easy to create with jQuery and PHP, and with new HTML5 FileReader API support, we can do client side file validation before even uploading the file to server. Today we are going to combine all these web features to make an Ajax based file uploader, which can be easily integrated into any HTML forms.  

Ajax file upload

Upload Form Markup

HTML contains file input field, upload button, progress bar and DIV element to output server responses. Only thing to notice here is “multipart/form-data” attribute, it is a data encoding method available in HTML and we always need to include this attribute in our HTML form tag, when creating file upload forms.

HTML
123456789101112

<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<input name="FileInput" id="FileInput" type="file" />
<input type="submit"  id="submit-btn" value="Upload" />
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="progressbox" >
<div id="progressbar"></div >
<div id="statustxt">0%</div>
</div>
<div id="output"></div>

jQuery and HTML5 File API

Since we are using jQuery, I’ve included jQuery form plugin in our upload form to make things easier. It offers so many options to manipulate form with minimal code, which is great thing, because we can focus on other things like HTML5 File API. The FileReader is a powerful new feature of HTML5, which lets us read the contents of files locally, validating file is easier than ever. Earlier people used different methods to achieve the same, but it was a daunting task.

We only need these few lines of jQuery code to actually send our file to server using Ajax, with jQuery Form plugin included in our page. No more code is required, but as you can see it also accepts various options such as “beforeSubmit“, “success“, “uploadProgress” etc. (You can find more options here). which can greatly extend the functionality of our form, we can just create block of functions and call them within the option.

JQUERY
1234567891011121314

$(document).ready(function() {
var options = {
	target:   '#output',   // target element(s) to be updated with server response
	beforeSubmit:  beforeSubmit,  // pre-submit callback
	success:       afterSuccess,  // post-submit callback
	uploadProgress: OnProgress, //upload progress callback
	resetForm: true        // reset the form after successful submit
}; 
 $('#MyUploadForm').submit(function() {
	$(this).ajaxSubmit(options);
	return false;
});
});

Checking HTML5 File API Browser support

Let’s write a beforeSubmit function, which will be called before uploading the file to server, and it is our important piece of code here, because we are going to use HTML File API in it, which will validate the file size and type locally. Since more and more browsers now support HTML FileReader, I think we should definitely use it more often in our upload forms.

JQUERY
123456789101112

function beforeSubmit(){
   //check whether client browser fully supports all File API
   if (window.File && window.FileReader && window.FileList && window.Blob)
	{
        }
        else
	{
	   //Error for older unsupported browsers that doesn't support HTML5 File API
	   alert("Please upgrade your browser, because your current browser lacks some new features we need!");
	}
}

Checking File size and type before upload using HTML5 File API

The following code accesses the browser File API support and checks whether the user is trying to upload right file type and its size is under the allowed limit. Older browsers will get an error message asking to upgrade their browser.

JQUERY
12345678910111213141516171819202122232425262728293031323334353637383940

function beforeSubmit(){
   //check whether client browser fully supports all File API
   if (window.File && window.FileReader && window.FileList && window.Blob)
	{
	   var fsize = $('#FileInput')[0].files[0].size; //get file size
           var ftype = $('#FileInput')[0].files[0].type; // get file type
		//allow file types
	  switch(ftype)
           {
            case 'image/png':
			case 'image/gif':
			case 'image/jpeg':
			case 'image/pjpeg':
			case 'text/plain':
			case 'text/html':
			case 'application/x-zip-compressed':
			case 'application/pdf':
			case 'application/msword':
			case 'application/vnd.ms-excel':
			case 'video/mp4':
            break;
            default:
             $("#output").html("<b>"+ftype+"</b> Unsupported file type!");
	     return false
           }
	   //Allowed file size is less than 5 MB (1048576 = 1 mb)
	   if(fsize>5242880)
	   {
	     alert("<b>"+fsize +"</b> Too big file! File is too big, it should be less than 5 MB.");
	     return false
	   }
        }
        else
	{
	   //Error for older unsupported browsers that doesn't support HTML5 File API
	   alert("Please upgrade your browser, because your current browser lacks some new features we need!");
           return false
	}
}

Progress Bar

It’s always a good idea to include a progress bar in our file uploader to track upload progress, since we are dealing with different files and unlike images, other files can be bigger in size and can take quite a long time to upload. The jQuery form plugin passes several progress information to our function (If supported by browser), which we will capture and use to animate our progress bar.

JQUERY
1234567891011
function OnProgress(event, position, total, percentComplete)
{
    //Progress bar
    $('#progressbox').show();
    $('#progressbar').width(percentComplete + '%') //update progressbar percent complete
    $('#statustxt').html(percentComplete + '%'); //update status text
    if(percentComplete>50)
        {
            $('#statustxt').css('color','#000'); //change status text to white after 50%
        }
}

Server side PHP

Once the file is successfully uploaded to server via the HTTP POST method, we can access the file information using PHP code. The information we need here are file name, type and size, using the information here too we double check for valid file size and type. And then using PHP move_uploaded_file function, we will move the file to a new location, then we can just add mySQL code to store information in the database.

Here’s the complete PHP code which does the server side task, you need to place this file along with upload HTML form page we created earlier, just point your Ajax form to this file.

PHP
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859

<?php
if(isset($_FILES["FileInput"]) &#038;&#038; $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
	############ Edit settings ##############
	$UploadDirectory	= '/home/website/file_upload/uploads/'; //specify upload directory ends with / (slash)
	##########################################
	
	/*
	Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini". 
	Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit 
	and set them adequately, also check "post_max_size".
	*/
	
	//check if this is an ajax request
	if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
		die();
	}
	
	
	//Is file size is less than allowed size.
	if ($_FILES["FileInput"]["size"] > 5242880) {
		die("File size is too big!");
	}
	//allowed file type Server side check
	switch(strtolower($_FILES['FileInput']['type']))
		{
			//allowed file types
            case 'image/png':
			case 'image/gif':
			case 'image/jpeg':
			case 'image/pjpeg':
			case 'text/plain':
			case 'text/html': //html file
			case 'application/x-zip-compressed':
			case 'application/pdf':
			case 'application/msword':
			case 'application/vnd.ms-excel':
			case 'video/mp4':
				break;
			default:
				die('Unsupported File!'); //output error
	}
	$File_Name          = strtolower($_FILES['FileInput']['name']);
	$File_Ext           = substr($File_Name, strrpos($File_Name, '.')); //get file extention
	$Random_Number      = rand(0, 9999999999); //Random number to be added to name.
	$NewFileName 		= $Random_Number.$File_Ext; //new file name
	if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
	   {
		// do other stuff
               die('Success! File Uploaded.');
	}else{
		die('error uploading File!');
	}
}
else
{
	die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
}

That’s it, I have tried to make this tutorial very simple, you can download the sample files from below and continue with testing. The demo you’ll see is from different tutorial, but works similar way and it only allows image files. If you have any suggestions please go ahead and leave your valuable comments, good luck!

Download Demo

  • 95 Comments

    Add Comment
    • Vihal
      It's really good article , easy and simple . But I am unable to understand how do I can use 3 different Image uploader controls with each progress bar and thumbs. example :https://ibb.co/xsdLc24
    • Arijit
      download link not working
    • Azul
      Hi, Thanks for the script. How can I display the name of the file to upload right after the button Browse ? Regards
    • João Antonio
      How I can upload .rar, .zip, and the office extension. Thanks
    • João Antonio Morgado Won Doelinger
      How i can do upload rar, zip, doc, xlsx and pptx? Thanks.
    • Tommaso
      For me It works fine, but I have a little problem with the file called processupload.php, when I try to store these two vars: $File_Name = strtolower($_FILES['FileInput']['name']); $File_Ext = substr($File_Name, strrpos($File_Name, '.')); into a file txt to read the value in second time, $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = $File_Name + "\n"; fwrite($myfile, $txt); $txt = $File_Ext + "\n"; fwrite($myfile, $txt); fclose($myfile); the result is always the same.... the value stored in txt are 0 and 0 double zero... and I don't understand why!!! Please help me ;)
    • Olidev
      Nice guide. But a form for uploading file in PHP can also be done without using AJAX (here is an example: https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/ ). Instead of AJAX, you can also use Angular or Vue. I would recommend using Vue.
    • Ali
      Thank u very much
    • Simon
      Hi, I need 4 seperate upload boxes (long story), I added $('#MyUploadForm1').submit(function() { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); and another set of forms etc etc but no joy, has anyone one done multiple upload boxes Thanks
    • Delino
      Am new here but not new in codes I must ask my self where was i. Nice work Boss