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.


Live Demo Download Source

Step 1 - The HTML

At first we need to create a simple file upload form.

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

  <meta charset="utf-8" />
  <title>Multiple File Upload with progress bar</title>

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

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

  <!-- status message will be appear here -->
  <div class="status"></div>
  
  <!-- multiple file upload form -->
  <form action="upload.php" method="post" enctype="multipart/form-data" class="pure-form">
    <input type="file" name="files[]" multiple="multiple" id="files">
    <input type="submit" value="Upload" class="pure-button pure-button-primary">
  </form>
  
  <!-- progress bar -->
  <div class="progress">
    <div class="bar"></div >
    <div class="percent">0%</div >
  </div>

</div>

  <!-- javascript dependencies -->
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/jquery.form.min.js"></script>
  
  <!-- main script -->
  <script type="text/javascript" src="js/script.js"></script>

</body>
</html>


Step 2 - jQuery

script.js file holds our JavaScript and jQuery codes. In this tutorial we are using jQuery.form plugin to submit our form through ajax request.

$(function() {
  /* variables */
  var status = $('.status');
  var percent = $('.percent');
  var bar = $('.bar');
  
  /* submit form with ajax request using jQuery.form plugin */
  $('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) {
      status.html(data.responseJSON.count + ' Files uploaded!').fadeIn();
    }

  });
});


Step 3 - PHP

Our upload.php file will receive uploaded files and it will do some file validations like max uploaded size and valid extensions. If files are pass the validations it will move files to upload folder and echo out number of successfully uploaded files with JSON response. If files contains any error or fail validation it simple will be skipped.

$max_size = 1024*200;
$extensions = array('jpeg', 'jpg', 'png');
$dir = 'uploads/';
$count = 0;

if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files']))
{
  // loop all files
  foreach ( $_FILES['files']['name'] as $i => $name )
  {
    // if file not uploaded then skip it
    if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
      continue;

      // skip large files
    if ( $_FILES['files']['size'][$i] >= $max_size )
      continue;

    // skip unprotected files
    if( !in_array(pathinfo($name, PATHINFO_EXTENSION), $extensions) )
      continue;

    // now we can move uploaded files
      if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $dir . $name) )
        $count++;
  }

  echo json_encode(array('count' => $count));

}
Note PHP's default max number of file upload is 20. That means you can not upload more than 20 files at once. If you want to allow more than 20 files you need to edit php.ini file and change max_file_uploads value.

31 comments:

  1. Simply awesome! Good job

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. trước Hỏa Lão chỉ có thể miễn cưỡng chống lại Địa Ma Lão Nhân mà thôi nhưng hiện tại tu vi thực lực của lão đã khôi phục tới cửu tinh Đấu Tôn, một mình lão giết Địa Ma Lão Nhân cũng không có vấn đề gì.

      Địa Ma Lão Nhân dường như cũng hiểu rõ điều này, nhìn thấy thực lực của Hỏa Lão đã khôi phục thành cửu tinh Đấu Tôn hắn nhanh chóng bao bọc một hắc mang quanh người mà lùi về phía sau.

      Nhạc Thành nhìn thấy Địa Ma Lão Nhân muốn chạy trốn thì khóe miệng nở ra một nụ mỉm cười, hắn không hề lo lắng, ở đây mình đã bố trí cấm chế, Địa Ma Lão Nhân muốn thoát khỏi thì rất khó khăn.

      - Xoẹt xoẹt.

      Nhạc Thdongtam
      mu moi ra hom nay
      tim phong tro
      http://nhatroso.com/
      nhạc sàn
      tổng đài tư vấn luật
      văn phòng luật hà nội
      tổng đài tư vấn luật
      thành lập công ty trọn gói
      http://we-cooking.com/
      chém gió
      trung tâm tiếng anhành đoán không sai, Địa Ma Lão Nhân bị một đòn của Hỏa Lão mà trọng thương thân hình nhanh như chớp nhảy về phía sau, tốc độ vô cùng nhanh như muốn bỏ chạy.

      Thân pháp của Nhạc Thành chuyển động, thân ảnh của hắn như một vòng sáng đuổi theo phía sau lưng của Địa Ma Lão Nhân.

      - Đáng chết, tại sao lại như vậy?

      Delete
  2. Thanks for you script.. Can you replace the script download or live demo? I try to write the code but not work...
    Maybe I'm wrong something ..

    ReplyDelete
  3. The script is not working with progress bar. The file will upload but will not show the upload bar or status. What am I doing wrong? Do I have to activate anything in PHP.ini?

    ReplyDelete
  4. works fine, but there is a mistake in your code.

    watch the curly braces at the end!

    In your code its:
    [..]
    echo json_encode(array('count' => $count));
    }


    but it has to be:
    [..]
    }
    echo json_encode(array('count' => $count));

    ReplyDelete
  5. Hi, I got a problem with this code. The progress bar doesn't work and after a sucessful upload of an image, there will be displayed {"count":1}.
    Any ideas?

    ReplyDelete
    Replies
    1. You need to jquery.form to correct this and also make sure all the css and js files are present. IT works for me

      Delete
  6. SITE CODE IS OK .. BUT THE SOME PROBLEMS IN ZIP FOLDER.

    ReplyDelete
  7. scripts.js needs to be edited to add the opening jquery cal for the function:

    Change "(function() {" to "$(function() {"

    ReplyDelete
    Replies
    1. Thanks Jason. Your comment made it work for me

      Delete
    2. Thanks Jason, your solution worked for me

      Delete
  8. Why the script uploads only 20 files, and no more, at once?

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. My program has 6 inputs, but a user may decide to upload only 4 images. When I post the names of the files using $_FILES, it will only show me the names of the uploaded images. I need to know which of the six images they decided not to use, so I need all six to show, even the blank ones.

    ReplyDelete
  11. How do anyone show the images on a website slideshow or by mysql and php where order by date image or name of the image.
    So that others can see the images in a good looking maner.

    ReplyDelete
  12. Is there any way to show the progress bar for each file being uploaded?

    ReplyDelete
  13. the code is working fine now... thanks jason to make error correction

    ReplyDelete
  14. The progress bar is not working, the js and css files are linked so really not sure what else the issue could be, can anyone help please in case I missed something

    ReplyDelete
  15. Muito, algum BR com problemas?

    ReplyDelete
  16. Hi
    This script rocks....
    However I struggle with getting more convenient error messages...
    Example: 'Your selected file is too large', This type of file are not allowed!' and so on.
    Any ideas?
    Any suggestion are more than welcome.
    /hhc

    ReplyDelete
    Replies
    1. files allowed are $extensions = array('jpeg', 'jpg', 'png'); I recommend to add .JPG, .PNG, . JPEG, and max php file I think is 2MB you need to change php inin max file size, I use 5 MB

      Delete
    2. Sorry I was not precise...
      What I meant was to get error message displayed on page for example saying 'Your selected file seems outside upload limitations'.....
      This needs modifications of script, which I struggle with...
      The standard PHP var $max_size, $extensions and PHP-ini settings I fully understand....

      Delete

Go to top