Multi Image/File upload in php and jquery

This tutorial for newbie php developer who are looking for a process to create multi file upload feature in php and jquery from scratch, In my few months back tutorial i talked about the normal single file upload feature with progress bar using php and jquery, So here i come up with the little advance trick which help you to upload file/image in bulk.

Please Note: The progress bar requires modern browsers that support HTML5 tags and XMLHttpRequest is a new HTML5 feature that adds more functionality to AJAX requests for transferring data between a client and a server.



Now Lets start tutorial step by step
Technology used: PHP, Jquery, Ajax

Directory Structure

+-js
---upload.js
+-upload
--index.php
--upload.php

Step:1- Create index.php file and write your html code and include jquery library. Don’t forget to create a directory upload where all uploaded files will be placed.



index.php

<?php
error_reporting(0);
?>
<!DOCTYPE html>
<html lang="en-US">
<title>Multi Image upload in php+ajax with progress bar!</title>
<meta charset="utf-8">
<meta name="Keywords" content="Multi Image upload in php and ajax with progress bar">
<meta name="Description" content="Multi Image upload in php and ajax with progress bar">
<body>
<div style="width:60%; margin:0 auto;">
<h3>Multi Image upload in php+ajax with progress bar! <a href="https://github.com/hiiamrohit/php_ajax_multi_file_upload_with_progressbar" target="_blank">Download</a></h3>
<div style="border:1px solid; padding:10px 10px 10px 10px; float:left; width:800px;">
<form enctype="multipart/form-data" id="myform" name="myform">  
   <b>Choose multiple image to upload.</b><br/>
    <input type="file"  name="file[]" id="image" multiple />
    <br>
   <font color=red>Note: Choose only .gif, .jpeg, .jpg, .png images only..!!</font><br/>  
    <input type="button" value="Upload images" class="upload" />
</form>
<div id="progBar" style="display:none;">
 <span id="fname" style="color:red;"></span>
  <progress value="0" max="100" style="width:750px; "></progress><span id="prog" style="font-weight:bold;">0%</span>
</div>
<div id="alertMsg" style="font-size:16px; color:blue; display:none;"></div>
<h3>List of uploaded files</h3>
<table border=1 width=100% id="tb" align="left">
<tr style="display:none;"><td colspan=2 ></td></tr>
<?php 
  $dir = "upload/";
  $i=0;
    foreach(glob($dir."{*.jpg,*.gif,*.png,*.jpeg}", GLOB_BRACE) as $file){ 
             echo "<tr id='row".$i."'><td><a href='".$file."' target='_blank'><img src='".$file."' width=200 height=200></a></td><td><a href='javascript:void(0);' id='delete' rmid='row".$i."' filename='".$file."'>Delete</a></td></tr>";
             $i++;    
}
?>
   </table>
  </div>
 </div>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="js/upload.js"></script>
 </body>
</html>

Step:2- Create file name upload.js under js folder which will handle all your client request and show progress bar for file upload in real time.

js/upload.js

$(function() {
 $(".upload").click(function() {
 var fl= $("input[name='file']");
 if(fl.val()=="") {
   flashMsg("Please choose image to upload."); 
   return false;
 }
 $("#progBar").show();
 $(this).attr('disabled','disabled');
   var form = new FormData($("#myform")[0]);
   var count = $("table#tb tr").length;
   $.ajax({
      url: 'upload.php',
      type: 'POST',
      data: form,
      processData: false, 
      contentType: false,
      dataType: 'json',
      xhr: function() {
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){
                        myXhr.upload.addEventListener('progress',progress, false);
                    }
                    return myXhr;
                },
      success: function(res) {
      if(res.type=='success') {
      var file = res.fileName;
        $("table#tb tr:first").before("<tr id='row"+count+"'><td><a href='upload/"+file+"' target='_blank'><img src='upload/"+file+"' width=200 height=200></a></td><td><a href='javascript:void(0);' id='delete' rmid='row"+count+"' filename='upload/"+file+"'>Delete</td></tr>");
        } 
        fl.val('');
        flashMsg(res.msg); 
        $("#file").val();
        $(".upload").removeAttr('disabled');
        $("#progBar").hide();
        resetProgressBar();
      },
      error: function(e) {
         alert(e.status+" error occurred to upload image!");
        window.location.href=window.location.href;
      }    
   });  
 });
 
 // Proress bar
 function progress(e){
        if(e.lengthComputable){
            $('progress').attr({value:e.loaded,max:e.total});
            var percentage = (e.loaded / e.total) * 100;
            $('#prog').html(percentage.toFixed(0)+'%');
        }
    }
 
    function resetProgressBar() {
        $('#prog').html('0%');
        $('progress').attr({value:0,max:100});
    }
 
// Flash message 
 function flashMsg(msg) {
        $("#alertMsg").fadeIn(1000).html(msg).fadeOut(5000);
 }
 
 // Delete function
$(document).on('click','#delete',function() {
    $(this).attr('href','javascript:void(0)');
    var filePath = $(this).attr('fileName');
    var rmid = $(this).attr('rmid');
    $(this).html("deleting..");
    $.ajax({
        url:'upload.php',
        type:'POST',
        dataType: 'json',
        data:{del:1,filePath:filePath},
        success:function(res){
                if(res.type=='success') {
                  $("table#tb tr#"+rmid).remove();
                  }
                  flashMsg(res.msg);
                },
        error: function(e) {
                alert(e.status+" error occurred to delete image!");
                window.location.href=window.location.href;
               } 
    });
});
 
 
});

Step:3- Now time to create our server side script called upload.php paste below code which handle our server request, apply upload validation and will place file in upload folder if upload become success.

upload.php

<?php
/*
* Author: Rohit Kumar
* Website: iamrohit.in
* Date: 12-08-2014
* App Name: Ajax file uploader
* Description: PHP + Ajax file uploader with progress bar
*/
error_reporting(0);
if(($_POST['del'] == 1) && (isset($_POST['del']))) {
  if (file_exists($_POST['filePath'])) {
   unlink($_POST['filePath']);
   $data = json_encode(array('type'=>'success', 'msg'=>'File deleted successfully.')); 
  } else {
   $data = json_encode(array('type'=>'error', 'msg'=>'Can not delete, File not exist.'));
  }
  echo $data;
  exit;
} else {
    $allowFile = array('image/png','image/jpeg','image/gif','image/jpg');
    if(in_array($_FILES["file"]["type"],$allowFile)) {
      if ($_FILES["file"]["error"] > 0) {
        $data =  json_encode(array('type'=>'error', 'msg'=>"Return Code: " . $_FILES["file"]["error"])); 
      } else {
        if (file_exists("upload/" . $_FILES["file"]["name"])) {
          $data = json_encode(array('type'=>'error', 'msg'=>$_FILES["file"]["name"] . " already exists. ")); 
        } else {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          $data = json_encode(array('fileName'=>$_FILES["file"]["name"],'msg'=>$_FILES["file"]["name"] . " uploaded successfully.", 'type'=>'success')); 
        }
      }
    } else {
    $data = json_encode(array('type'=>'error','msg'=>"Oh! Oh! Oh! Bad file type."));
    }
    echo $data;
} 
 
?>

If you have created and configured all files successfully time to test our code on browser. You can also see live working demo by clicking on demo button and download source code.

Hope this will help you to add file upload feature in your website..!!

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.