How to Create File Upload Progress Bar Using jQuery and PHP.

0

It is very simple getting the server file upload process every few second and increasing the bar color using jquery css property. Just take a look at this code. You may also like How to Animated progress bar using jquery, html and css and How to get file size in PHP.

HTML Code

<form action="upload.php"id="myForm" name="frmupload" method="post" enctype="multipart/form-data">
    <input type="file" id="upload_file" name="upload_file" />
    <input type="submit" name='submit_image' value="Submit Comment" onclick='upload_image_php();'/>
</form>
<div class="progress" id="progress_div">
    <div class="bar" id="bar1"></div>
    <div class="percent" id="percent1">0%</div>
</div>
<div id="output_image"></div>

CSS Code

<style>
    .progress 
    {
      display:none; 
      position:relative; 
      width:400px; 
      border: 1px solid #ddd; 
      padding: 1px; 
      border-radius: 3px; 
    }
    .bar 
    { 
      background-color: #B4F5B4; 
      width:0%; 
      height:20px; 
      border-radius: 3px; 
    }
    .percent 
    { 
      position:absolute; 
      display:inline-block; 
      top:3px; 
      left:48%; 
    }
</style>

jQuery Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script> 
<script>
    function upload_image_php() 
    {
      var bar = $('#bar');
      var percent = $('#percent');
      $('#myForm').ajaxForm({
        beforeSubmit: function() {
          document.getElementById("progress_div").style.display="block";
          var percentVal = '0%';
          bar.width(percentVal)
          percent.html(percentVal);
        },

        uploadProgress: function(event, position, total, percentComplete) {
          var percentVal = percentComplete + '%';
          bar.width(percentVal)
          percent.html(percentVal);
        },

            success: function() {
          var percentVal = '100%';
          bar.width(percentVal)
          percent.html(percentVal);
        },

        complete: function(xhr) {
          if(xhr.responseText)
          {
            document.getElementById("output_image").innerHTML=xhr.responseText;
          }
        }
      }); 
    }
</script>

PHP Code (upload.php)

<?php
if(isset($_POST['submit_image']))
{
  $uploadfile=$_FILES["upload_file"]["tmp_name"];
  $folder="images/";
  move_uploaded_file($_FILES["upload_file"]["tmp_name"], $folder.$_FILES["upload_file"]["name"]);
  echo '<img src="'.$folder."".$_FILES["upload_file"]["name"].'">';
  exit();
}
?>