File Upload with Ajax

File Upload with Ajax

Advert

Single file upload system and multiple file uploading scripts just served 100 thousand views individually since I posted them, I cannot be happier than this. I did receive a few comments and PM to give a shot on Upload with AJAX, so here it is File Upload with Ajax

This is the basic AJAX file uploading to demonstrate how uploading can be done on AJAX, I will come up with advance and multiple uploading script soon.

Github Download Live Demo

The concept

Unlike the ordinary file upload where you submit the file and its processed, most of the action happens in back-end and the front end works are completed by Web Browsers, but in AJAX file uploads is of 2 parts

  1. Client Side code
  2. Server Side code

You need to build both, In client side you gonna have to get the file packed it into a package to be sent over the internet to the server. In the Server side you need to have a system to receive the POST request & process the receiving file and save it. For server side I'm using my previous script Single file upload system, the code is simple and the article has good descriptions of how it works.

I'm using Jquery for the making the selection area and changing the message in the front end part, ( I was lazy) you can do these tasks using document.querySelector().

Let's get started.

The HTML

All you need is a

to get the HTML ready, I have used a little styles to make it look pretty so it feels like a page with upload function.

<form>		
	<div id="drop-box">
 	<p>Select Files</p>
  </div>
	<input type="file" name="upl" id="upl" />
</form>
CSS-Multiple-Borders wondering how to Set CSS Multiple Borders

Javascript

This is what makes the AJAX possible, the front-end java script that gets the file wraps it into a package and send it over the Internet to server. We are gonna add a few functions to make the user's life easy. At the end of the day that is what every one needs.

  • Prevent browser to take default actions like form submit and get the actions done via AJAX.
  • Trigger choose file button when clicked in upload area. Only if you are not using the default button.
  • Auto submit form once the file is uploaded. You might have some more fields which needs to filled before the form submits so make sure you do what is necessary.
  • That is all for this tutorial, you can have more

$(function(){
 $("#drop-box").click(function(){
   $("#upl").click();
 });
 // trigger the choose file button when clicked in the blue box

 // To prevent Browsers from opening the file when its dragged and dropped on to the page
 $(document).on('drop dragover', function (e) {
  e.preventDefault();
  });  

 // Add a listener to check if a file is chosen to trigger the upload action to call function fileUpload
 $('input[type=file]').on('change', fileUpload);
});

These codes will ensure the users get a good experience and avoids un necessary actions of submit. Lets move on to the uploaded part. I'll brief out what is going in here, also added comments in the code for easy understanding.

  • Get the files selected, in this case we have functions to upload a single file but the functions in this area remains almost same even for multiple files, but now its just a single file processing.
  • Create a FormData object ( More on FormData in Mozilla Dev Network). This is used to construct pairs vales which forms the data for the AJAX request.
    FormData uses different argument to handle string, File and blog refer the MDN link for more info.
    For tiles it takes 3 arguments formData.append(name, file, filename)
  • Traverse the files and do verifications for file type, Size and more. This is not a trustful verification it's always recommended to have a verification in back end or the server before processing the data
  • That is all for this tutorial, you can have more

function fileUpload(event){  
 $("#drop-box").html("

"+event.target.value+" uploading...

"); //to notify user the file is being uploaded files = event.target.files; // get the selected files var data = new FormData(); // Form Data check the above bullet for what it is var error = 0; // Flag to notify in case of error and abort the upload // File data is presented as an array. In this case we can just jump to the index file using files[0] but this array traversal is recommended for (var i = 0; i < files.length; i++) { var file = files[i]; if(!file.type.match('image.*')) { // Check for File type. the 'type' property is a string, it facilitates usage if match() function to do the matching $("#drop-box").html("

Images only. Select another file

"); error = 1; }else if(file.size > 1048576){ // File size is provided in bytes $("#drop-box").html("

Too large Payload ( < 1 Mb). Select another file

"); error = 1; }else{ // If all goes well, append the up-loadable file to FormData object data.append('image', file, file.name); // Comparing it to a standard form submission the 'image' will be name of input } } }

Now we are left with filtered and wrapped data, lets get the trigger to send the wrap to server. the following code must be inside the fileUpload function.

if(!error){
 var xhr = new XMLHttpRequest();     
 // Create a new XMLHttpRequest
 xhr.open('POST', 'upload.php', true);  
 // File Location, this is where the data will be posted
 xhr.send(data);
 xhr.onload = function () {                  
 // On Data send the following works
  if (xhr.status === 200) {
   $("#drop-box").html("

File Uploaded. Select more files

"); } else { $("#drop-box").html("

Error in upload, try again.

"); } }; }

This is everything to do with an AJAX file upload, but this won't save the files to server as you would want to. You need to process the receiving post request in upload.php and get the processing done there.

I have already written an article on Single file upload system, same code can be used here as well. In there we were posting to same file but here its on different file and the request is send via Javascript. Both these changes does not effect the functioning of the code so we are good to go ahead.


 1048576){
  $errors[]='File size must be less than 1MB';
 }				
 if(empty($errors)==true){
  move_uploaded_file($file_tmp,"images/".$file_name);
 }else{
  print_r($errors);  // not necessary because we are not checking for the server response in the front end.
 }
}
?>

The output of file doesn't matter since we are not using the response of the XMLHttpRequest to inform the user the status of upload, though it won't be big issue. The system informs success if the server responds with a 200 status no matter what happens to the file. So this is a basic upload system using AJAX, you are good to use this with your projects, but this lacks some functions.

Github Download Live Demo

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. Development Environment for Django in Docker Compose

     
  2. How Online Reviews Impact Local SEO

     
  3. 3 Money-Saving Tips For Your Company

     
  4. Domain Authority

     
  5. Public Endpoint in Django Rest Framework

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.

Powered by FeedBurner