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));

Comments

  1. How to increase max size? please help I need upload HD PIC LIKE 5MB
    OR 4608 * 3456

    ReplyDelete
    Replies
    1. If you have access to your php.ini file then change upload_max_filesize = 5M
      and next change $max_size = 1024*1024*5 on php script

      Delete
    2. How to get access in php.ini file? Pls tell. I'm using windows 10 XAMPP

      Delete
    3. Ok now tell me what should I edit in php.ini file to get max size?

      Delete
  2. Looks great!! Thanks!

    ReplyDelete
  3. Nice Post...helpful!!!

    ReplyDelete
  4. How i will make this for audio(mp3) files?

    ReplyDelete
  5. Hallo, I am from Indonesia. Sorry if my english is wrong. I just wanted to thank you, because finally I found this tutorial for 3 years, I think this is the best and perfect for me, simple but powerful. Very great post

    ReplyDelete
  6. Thanks for script
    How can I integrate this progressbar into kleeja script

    ReplyDelete
  7. can you tell me how to get link ? of image uploaded ?
    this is tutorial is great

    ReplyDelete
  8. Is it possible to show decimals values too in the percentage bar? I need that :)

    ReplyDelete
  9. Hello, can you let me know how can I upload the file size up to 200 MB?
    I tried to change to following information, but it's not working. Can you help?
    $max_size = 1024*1024*200

    ReplyDelete
    Replies
    1. hey, did you fix the problem? i have same problem too. i need to change the size to 500mb or 1TB. phozeex@gmail.com

      Delete
    2. You need to change your PHP configuration for big files in your php.ini

      http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize
      http://www.php.net/manual/en/ini.core.php#ini.post-max-size
      http://www.php.net/manual/en/info.configuration.php#ini.max-input-time

      Delete
    3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry.

      Delete
  10. how to change the file upload size to 500mb? please help
    its just keep saying Upload Fail: File not uploaded!

    i made change on upload.php file:

    $valid_exts = array('jpeg', 'jpg', 'png', 'psd', 'pdf', 'zip', 'gif'); // valid extensions
    $max_size = 512000 * 524288000; // max file size (512000kb)
    $path = 'uploads/'; // upload directory

    what else i have to do?

    phozeex@gmail.com

    ReplyDelete
    Replies
    1. You have to set the upload_max_filesize to the required size in php.ini.
      Or you can pro grammatically set it in your script too. Google for it.

      Delete
  11. For some weird reason the file is auto rotated to fit box in preview. how can I disable that?

    ReplyDelete
  12. Works Great !

    Found a small issue, after uploading image, the message is shown "Image Successfully uploaded!" but the progress bar shows 60% completed.
    I've screenshot to help replicate it but not sure where to attach with this post.

    ReplyDelete
  13. I want to upload four pictures with the same site. I know how to change the html-site (rename the ID's). But I don't know how to change the script.js. I don't want to write the function four times. Can me help somebody?

    ReplyDelete
  14. looks very nice.....
    downloaded source code zip is having some problem, its not extracting.
    please upload correct zip file.

    Thanks in Advance

    ReplyDelete
  15. here is a zip file of the code.. https://drive.google.com/file/d/0BzI3iLzL-4VUaHdCTHViLUFEeFE/edit?usp=sharing
    now does anyone know how to change the size of the preview image that i am getting on the front page just above the upload button...
    i have tried to set width and height but it is not working...
    reply asap....

    ReplyDelete
  16. I would like to send you 50 dollars by PayPal for your helping me to find a solution…

    I have your very nice ‘Multiple File Upload with Progress Bar’ working on my site. It displays the progress bar and uploads files properly.

    MY NEED:
    When it finishes the upload, I need for it to refresh to a different page within my site… “mypage.php?var1=this&var2=that”

    FYI:
    I must have corrupted something, because now, it does not display {count:n} when upload is complete and the URL in the browser location field does not change FROM “/multiple-file-upload-progress-bar/“ TO “/multiple-file-upload-progress-bar/upload.php”

    If you can help, please tell me how to contact you privately so that I can send the money and site access information privately. I can be reached creekriot at gmail.

    Thank you!
    - Stan

    ReplyDelete
    Replies
    1. hey . i know this is old. but this is for some who has not solved this problem. the error are in the script.js in this line
      after you downloaded the zip file . you will noticed in this line >
      /* set data type json */
      dataType:'json', .there a some sort of a html entities appeared after the ":" . juts rid of it . and everyone's happy ! :D

      Delete
  17. Nice, very nice, do you have the same example with multiple files? thanks.

    ReplyDelete
    Replies
    1. yeah! see http://www.w3bees.com/2013/12/multiple-file-upload-with-progress-bar.html

      Delete
  18. Hi. This is very nice. But i'm not able to download the source files from the provided link. It says files are corrupted. It would be a great help if u provide me a working link to these source files.

    ReplyDelete
  19. how to change name with new name from input type text and save in database. thank

    ReplyDelete
  20. Lớp học kế toán tổng hợp thực hành tại hải phòng
    Lớp học kế toán tổng hợp thực hành tại biên hòa đồng nai
    Lớp học kế toán tổng hợp thực hành tại vinh nghệ an
    Lớp học kế toán tổng hợp thực hành tại hải dương
    Lớp học kế toán tổng hợp thực hành tại ninh bình
    Lớp học kế toán tổng hợp thực hành tại hưng yên
    Lớp học kế toán tổng hợp thực hành tại phú thọ
    Lớp học kế toán tổng hợp thực hành tại hà nam
    Lớp học kế toán tổng hợp thực hành tại vĩnh phúc
    Lớp học kế toán tổng hợp thực hành tại bắc giang
    Lớp học kế toán tổng hợp thực hành tại thái nguyên
    Lớp học kế toán tổng hợp thực hành tại thái bình
    Lớp học kế toán tổng hợp thực hành tại nam định
    Lớp học kế toán tổng hợp thực hành tại thanh hóa
    Lớp học kế toán tổng hợp thực hành tại tphcm
    Lớp học kế toán tổng hợp thực hành tại bắc ninh
    Lớp học kế toán tổng hợp thực hành tại hà đông
    Lớp học kế toán tổng hợp thực hành tại long biên
    Lớp học kế toán tổng hợp thực hành tại thanh xuân
    Lớp học kế toán tổng hợp thực hành tại cầu giấy
    khóa học kế toán toán dành cho giám đốc và nhà quản lý
    dịch vụ thành lập doanh nghiệp công ty trọn gói
    dịch vụ thành lập doanh nghiệp công ty tại hải phòng
    dịch vụ tạm ngừng giải thể doanh nghiệp
    dich vu ke toan thue
    dich vu lam bao cao tai chinh

    ReplyDelete
  21. Wow. This really made my day. Thanks a lot!
    JavaScript Training Courses JavaScript Training Courses Javascript Online Training Javascript Online Training

    Javascript Online Training JQuery Online Training JQuery Online Training Javascript Online Training

    ReplyDelete
  22. Yeah i used this form and it works but dont show progress bar, but hey it works
    type="text/javascript" src="http://malsup.github.com/jquery.form.js">

    ReplyDelete
  23. Mệt mỏi quá. . . . . .
    Cả một ngày bận rộn, tất cả mọi việc đều loạn hết lên, lúc cô đến kiểm tra, không có một việc nào làm cô vừa lòng, xem ra cô phải mất rất nhiều thời gian ở Cao Hùng đây.
    Mệt muốn chết, cô không nhớ tới đến việc tắm rửa, rất muốn đi ngủ luôn Tiếng anh cho người đi làm
    Tiếng anh cấp tốc
    Luyện thi toeic tại hà nội
    Tiếng anh cho người lớn tuổi
    Tiếng anh cho người mới bắt đầu
    Học tiếng anh tại hà nội
    dạy tiếng anh cho doanh nghiệptốt, nhưng là cô còn chưa có tháo trang sức, ít nhất cũng phải tháo kính áp tròng, rửa mặt rồi mới ngủ tiếp, bằng không sáng sớm ngày mai cô sẽ bị dọa chết bởi khuôn mặt của mình mất thôi, mắt cô cũng không thể mở nổi.

    ReplyDelete
  24. Thanks for the always useful information. This is great information to help garage type SEO people like me.Core Temp 1.10.2

    ReplyDelete
  25. Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.

    ReplyDelete
  26. • Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online Training Bangalore

    ReplyDelete
  27. Thanks for your sharing. Hope you can contribute more quality posts to this page helix jump

    ReplyDelete
  28. The post was really very good.Thanks for sharing
    prestige elysian

    ReplyDelete
  29. Alleyaaircool is the one of the best home appliances repair canter in all over Delhi we deals in repairing window ac, Split ac , fridge , microwave, washing machine, water cooler, RO and more other home appliances in cheap rates

    Window AC Repair in vaishali
    Split AC Repair in indirapuram
    Fridge Repair in kaushambi
    Microwave Repair in patparganj
    Washing Machine Repair in vasundhara
    Water Cooler Repair in indirapuram
    RO Service AMC in vasundhara
    Any Cooling System in vaishali
    Window AC Repair in indirapuram

    ReplyDelete

  30. Get the most advanced RPA Course by RPA Professional expert. Just attend a FREE Demo session about how the RPA Tools get work.
    For further details call us @ 9884412301 | 9600112302
    RPA training in chennai | UiPath training in chennai

    ReplyDelete
  31. the wedding day is a very important day and make your day special and good with Bridal Boutiques and Bridal Wear Designers

    ReplyDelete
  32. Good post i am pretty much pleased with your good post.You put really very helpful information

    คาสิโนออนไลน์ที่น่าเชื่อถือและมีความเป็นมืออาชีพที่สุดในตอนนี้
    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร สล็อตออนไลน์ กับทางทีมงานของเราเพียงเท่านั้น
    ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสล็อตออนไลน์ >>> Goldenslot
    สนใจร่วมสนุกกับ คาสิโนออนไลน์ คลิ๊กได้เลย
    มีทั้งคาสิโนออนไลน์ หวยออนไลน์ ฟุตบอลออนไลน์ สล็อตออนไลน์ และอื่นๆอีกมากมาย

    ReplyDelete

  33. Get the most advanced Hadoop Course by Professional expert. Just attend a FREE Demo session.
    call us @ 9884412301 | 9600112302
    Hadoop training in chennai | Hadoop training in velachery

    ReplyDelete

Post a Comment

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.

Force File Download with PHP

If you want to control or track your downloadable contents then a force file downloader script can give you more option. Especially if you want make images or other stemming contents like music file (mp3, wav, ogg), video files (flv, mp4, ogg, 3gpp), css, JavaScripts or even a php file downloadable then you must need to use a force file downloader script.
In this post I am going to share a simple but useful force file downloader script.