Skip to main content

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin. It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.


Live Demo Download Source

Step 1 - The HTML

As usual, we will start with HTML markup.

<!doctype html>
<html lang="en">
<head>

  <meta charset="utf-8">
  <title>File Upload with Progress Bar</title>

  <!--style sheets-->
  <link rel="stylesheet" type="text/css" href="css/pure.css">
  <link rel="stylesheet" type="text/css" href="css/style.css">

  <script type="text/javascript">
    // select file function only for styling up input[type="file"]
    function select_file(){
      document.getElementById('image').click();
      return false;
    }
  </script>

</head>
<body>
  <div class="container">

    <!--status message will appear here-->
    <div class="status"></div>

    <!--image upload form-->
    <form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">

      <div class="upload">
        <a onclick="select_file()" class="pure-button">Choose a Image</a>
        <input id="image" type="file" name="image" >
      </div>

      <!--image preview-->
      <img src="" style="display:none">

      <input class="pure-button pure-button-primary" type="submit" value="Upload!">
    </form>

    <!--progress bar-->
    <div class="progress">
          <div class="bar"></div >
          <div class="percent">0%</div >
      </div>

  </div>

  <!--scripts include-->

  <!-- jQuery Library-->
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

  <!-- jQuery Form Plug in -->
  <script type="text/javascript" src="js/jquery.form.min.js"></script>

  <!-- our main javascript file -->
  <script type="text/javascript" src="js/script.js"></script>

</body>
</html>

The form is the heart of this html page. It will allow as to upload file. Before closing body tag I have inserted three JavaScript files. These are jQuery library, jQuery form plugin and our main script file.



Step 2 - jQuery

This is our main JavaScript file. There are two part of this file. The first one is image preview (based on HTML5 FileReader api) and second one is jQuery AJAX form submit (based on jQuery Form plugin).

$(document).ready(function() {
  /* variables */
  var preview = $('img');
  var status = $('.status');
  var percent = $('.percent');
  var bar = $('.bar');

  /* only for image preview */
  $("#image").change(function(){
    preview.fadeOut();

    /* html FileRender Api */
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("image").files[0]);

    oFReader.onload = function (oFREvent) {
      preview.attr('src', oFREvent.target.result).fadeIn();
    };
  });

  /* submit form with ajax request */
  $('form').ajaxForm({

    /* set data type json */
    dataType:  'json',

    /* reset before submitting */
    beforeSend: function() {
      status.fadeOut();
      bar.width('0%');
      percent.html('0%');
    },

    /* progress bar call back*/
    uploadProgress: function(event, position, total, percentComplete) {
      var pVel = percentComplete + '%';
      bar.width(pVel);
      percent.html(pVel);
    },

    /* complete call back */
    complete: function(data) {
      preview.fadeOut(800);
      status.html(data.responseJSON.status).fadeIn();
    }

  });
});


Step 3 - PHP

We need to handle uploaded file from server side. The upload.php file holds the file upload functionality. Because we are working with JSON data type that's why fist we need to set content type json.

header('Content-type: application/json');

$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 200 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
  if( @is_uploaded_file($_FILES['image']['tmp_name']) )
  {
    // get uploaded file extension
    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    // looking for format and size validity
    if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
    {
      // unique file path
      $path = $path . uniqid(). '.' .$ext;
      // move uploaded file from temp to uploads directory
      if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
      {
        $status = 'Image successfully uploaded!';
      }
      else {
        $status = 'Upload Fail: Unknown error occurred!';
      }
    }
    else {
      $status = 'Upload Fail: Unsupported file format or It is too large to upload!';
    }
  }
  else {
    $status = 'Upload Fail: File not uploaded!';
  }
}
else {
  $status = 'Bad request!';
}

// echo out json encoded status
echo json_encode(array('status' => $status));

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery . Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar. We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code . multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.