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.

53 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
    2. Where do we need to jquery.form to correct this?

      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
    Replies
    1. not alone Ian. tried adding the $ to script.js as recommended and still not working for me

      Delete
    2. Got a *mostly* working version. Not sure how to get it to you.

      Delete
  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
  17. Any reason that I am not able to use it to allow MP4 files? I tried to include it in
    $extensions = array('jpeg', 'jpg', 'png', 'JPEG', 'JPG', 'PNG', 'MP4', 'mov');
    However whenever I try to upload MP4 files, I get a '0 files were uploaded' error as it prevents even my PNG files from uploading.

    ReplyDelete
  18. I had to change two things:
    1. $(function () .... (in script.js)
    2 encoding to UTF-8 without BOM
    and everything works properly. :)

    ReplyDelete
  19. I had to change two things:
    1. $(function () .... (in script.js)
    2 encoding to UTF-8 without BOM
    and everything works properly. :)

    ReplyDelete
  20. Ap 10th Results 2016

    Many thanks for you post , this is good post i find for today......

    ReplyDelete
  21. Good post. This is a very clear, informative and helpful post.
    Latest Railway Jobs 2016

    ReplyDelete

  22. Railway Jobs

    Thanks for sharing such a nice article Sarkari Result your idea is mind blowing that's why i would like to appreciate your work.

    ReplyDelete
  23. Dapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule

    and obat vig power capsule

    ReplyDelete
  24. Wow amazing i saw the article with execution models you had posted. This type of examples will clearly explain their program. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.

    Salesforce Training

    ReplyDelete
  25. Thanks for worth sharing, can you help on how to send image paths to mysql database please?

    ReplyDelete
  26. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.

    Digital Marketing Training

    ReplyDelete
  27. I am truly pleased to glance at this weblog posts which contains lots of valuable data, thanks for providing such data.

    Latest Govt Jobs Recruitment 2016

    ReplyDelete
  28. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care.As always, we appreciate your confidence and trust in us.. SAP Training in chennai

    ReplyDelete

Go to top