Ajax Multiple Image upload using Javascript and PHP

In this post we will see how to create ajax image upload using javascript and PHP. I have already published tutorial on drag drop file upload using jQuery and Dropzone.js, but this script will have its own significance as it’s purely javascript based and uses jQuery UI for progress bar uploader. There’s a lot that we need to do in order to create a good file (image or any other file) uploader. In this tutorial we will focus on uploading images using javascript and PHP. This script uploads image to the server as soon as user selects the image file, i.e. image uploading happens without refreshing the page. It works in most of the browser including IE9, Firfox, Chrome, Opera. You can call this script version 1.0 because there are many things to do and we will keep implementing them one by one and will create a flexible and secure image uploader using javascript and php.

ajax image upload javascript php

          Live Demo      Download

Let’s have a look what this script does for you:

1) Uploads all image types to your server directory.

2) Uploads multiple images at the same time. Use Ctrl key to select multiple images/

3) Restricts other file types from getting uploaded by displaying a proper message.

4) Uploads images using Ajax i.e. without refreshing the page (You don’t need to hit upload button).

5) Renames the file by appending a random number string with file name. This helps so that user can upload files with the same name without getting any error message.

6) Displays progress meter to show percentage of image uploaded.

7) Displays proper messages if image is successfully uploaded or not.

8) Displays thumbnails of all images which are successfully uploaded.

Lets try to understand its code. So we have index.php file simply to display an option to select image and it calls custom.js which makes sure that file being uploaded is an image and processes it via Ajax. Then this file is passed to form action i.e. upload.php which renames the file by appending random string and uploads it to server directory. jQuery UI is used to display progress bar.

Below is our code for index.php:

</p>
<div id="fupload">
 <h2>Ajax Image upload</h2>
<form action="upload.php" method="post" enctype="multipart/form-data" name="fileupload" id="fileupload">
<input onchange="fileread(this)" name="filename[]" id="filename" type="file" multiple />
<input type="submit" id="submit" value="Upload" />
</form>
<div id="progress_status">
<div id="progressbar" class='progress'></div><div id="status"></div></div>
<div id="complete"></div>
<div id="thumb"></div>
<div id="error"></div>
</div>
<p style="text-align: justify;">

Now custom.js takes action as soon as an image file is selected.

Below is our code for custom.js: 

</p>
function fileread(file) {
var fsize = file.files[0].size;
var fname = file.files[0].name;
var ftype = file.files[0].type;
 var fielArray = ["image/png", "image/jpeg", "image/gif", "image/jpg"];
 var fileTrue = fielArray.indexOf(ftype);
if(fileTrue>=0){
 var reader = new FileReader();
 reader.element = $(file).parent().find('thumb');
 reader.onload = function(e) {
 var div = document.getElementById("thumb");
 div.innerHTML = "<img class='thumb' src='" + e.target.result + "'" +
 "title='" + fname + "'/>";

var formData = new FormData();
 for (var i = 0; i < file.files.length; i++) {
 var fileup = file.files[i];
 // Check the file type.
 if (!fileup.type.match('image.*')) {
 continue;
 }
 // Add the file to the request.
 formData.append('filename[]', fileup, fileup.name);

}
 uploadajax(formData)
 };
 reader.onerror = function(e) {
 alert("error: " + e.target.error.code);
 };
 reader.readAsDataURL(file.files[0]);
 }else{
 document.getElementById("error").innerHTML = "Incorrect file format, Please select an image file format..";
}
 }


 function uploadajax(formData){
 var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function () {
 if (xhr.status === 200) {
 //console.log(xhr.responseText);
 } else {
 alert('An error occurred!');
 }
};

xhr.upload.addEventListener("progress", imageprogress, false);
xhr.addEventListener("load", Completed, false);
xhr.addEventListener("error", failstatus, false);
 xhr.addEventListener("abort", Abortedstatus, false);
xhr.send(formData);

}

 function imageprogress(event){
 document.getElementById('complete').style.display = 'none';
document.getElementById('progress_status').style.display = 'block';
 //document.getElementById("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
 var percent = (event.loaded / event.total) * 100;
 document.getElementById("status").value = Math.round(percent);
 $("#progressbar").progressbar({value: document.getElementById("status").value});
 document.getElementById("status").innerHTML = Math.round(percent)+"%";
}
<p style="text-align: justify;">

Finally upload.php is called via ajax, below is its code:

</p>
<?php
if(isset($_FILES['filename']))
{
 $Dest = dirname(__FILE__).'/upload/';
 if(!isset($_FILES['filename']) || !is_uploaded_file($_FILES['filename']['tmp_name'][0]))
 {
 die('Something went wrong with Upload!');
 }
 $RandomNum = rand(0, 9999999999);

 $ImageName = str_replace(' ','-',strtolower($_FILES['filename']['name'][0]));
 $ImageType = $_FILES['filename']['type'][0]; //"image/png", image/jpeg etc.

 $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
 $ImageExt = str_replace('.','',$ImageExt);

 $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);

 //Create new image name (with random number added).
 $NewName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

 move_uploaded_file($_FILES['filename']['tmp_name'][0], "$Dest/$NewName");

 $base_path="http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
 $base=$base_path.'/'.'upload/'.$NewName;
 //echo '<img src="'.$base.'">';
 echo "<div id='sucess' class='sucess' > Successfully uploaded.</div>";
 }
?>
<p style="text-align: justify;">

You are all done. This will create a super flexible multiple image file uploader with javascript and PHP taking advantage of ajax. Suggest us feature that you’d like to see in next version of this script. We will create a super awesome file management system which will be launched in near future. Also share in comments if this script helps you in a way or the other. You can download the code and change it the way you want to as per your need.

6 thoughts on “Ajax Multiple Image upload using Javascript and PHP”

  1. It does not upload multiple files, only file will be uploaded and saved in upload folder.
    I will try to 3-4 images at one time but it will not uploaded only one of them is uploaded on folder

    1. Hi Ashutosh,

      Thanks for notifying this, we will fix this in next version of this tutorial with some extra feature like database connectivity to store image information in DB.

      Thanks:
      Sanjeev

  2. This is not useful for store multiple images in database because only one image is store in database.How can i store multiple images in database.Please Solve my problem.

  3. I guess everybody fixed it but there is an error

    upload.php:23

    it should be “$Dest$NewName” and NOT “$Dest/$NewName”

Comments are closed.