Image/File Upload with Progressbar Using PHP & Jquery

In this post i am going to talk about very useful script written in php and jquery that is image/file upload with progress bar.I have created a very minimal code without any big uploading libraries.

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.


This tutorial will teach you file uploading feature with progress bar in php and jquery from core, Every application need file/image uploading feature most of the time like change profile picture without refresh page, upload reports etc. So advance browser and html now support progress bar, So that you can easily create this feature from scratch and add in your website according to your need.

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

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>Image upload in php+ajax with progress bar!</title>
<meta charset="utf-8">
<meta name="Keywords" content="Image upload in php and ajax with progress bar">
<meta name="Description" content="Image upload in php and ajax with progress bar">
<body>
<div style="width:60%; margin:0 auto;">
<div style="border:1px solid; padding:10px 10px 10px 10px; float:left; width:800px;">
<form enctype="multipart/form-data" id="myform">  
   <b>Choose Image to upload.</b><br/>
    <input type="file"  name="file" id="image" />
    <br/>
   <font color=red>Note: Choose only .gif, .jpeg, .jpg, .png images only..!!</font><br/> 
    <input type="button" value="Upload image" class="upload" />
</form>
<div id="progBar" style="display:none;">
  <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
* Date: 12-08-2014
* Website: iamrohit.in
* 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(empty($_FILES["file"]["name"])) {
      echo $data = json_encode(array('type'=>'error','msg'=>"Please choose file to upload."));
      exit;
    }
    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 all the 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.

If You are looking for multi image upload script follow below link.

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.