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




Multi Image upload in php+ajax with progress bar!




Multi Image upload in php+ajax with progress bar! Download

Choose multiple image to upload.

Note: Choose only .gif, .jpeg, .jpg, .png images only..!!

List of uploaded files

"; $i++; } ?>
Delete

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("Delete");
        } 
        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

'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.