PHP Ajax Upload Progress Bar

25,363

Solution 1

Introduction

The PHP Doc is very detailed it says

The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.

All the information you require is all ready in the PHP session naming

  • start_time
  • content_length
  • bytes_processed
  • File Information ( Supports Multiple )

All you need is to extract this information and display it in your HTML form.

Basic Example

a.html

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
    var intval = null;
    var percentage = 0 ;
    function startMonitor() {
        $.getJSON('b.php',
        function (data) {
            if (data) {
                percentage = Math.round((data.bytes_processed / data.content_length) * 100);
                $("#progressbar").progressbar({value: percentage});
                $('#progress-txt').html('Uploading ' + percentage + '%');

            }
            if(!data || percentage == 100){
                $('#progress-txt').html('Complete');
                stopInterval();
            }
        });
    }

    function startInterval() {
        if (intval == null) {
            intval = window.setInterval(function () {startMonitor()}, 200)
        } else {
            stopInterval()
        }
    }

    function stopInterval() {
        if (intval != null) {
            window.clearInterval(intval)
            intval = null;
            $("#progressbar").hide();
            $('#progress-txt').html('Complete');
        }
    }

    startInterval();
</script>

b.php

session_start();
header('Content-type: application/json');
echo json_encode($_SESSION["upload_progress_upload"]);

Example with PHP Session Upload Progress

Here is a better optimized version from PHP Session Upload Progress

JavaScript

$('#fileupload').bind('fileuploadsend', function (e, data) {
    // This feature is only useful for browsers which rely on the iframe transport:
    if (data.dataType.substr(0, 6) === 'iframe') {
        // Set PHP's session.upload_progress.name value:
        var progressObj = {
            name: 'PHP_SESSION_UPLOAD_PROGRESS',
            value: (new Date()).getTime()  // pseudo unique ID
        };
        data.formData.push(progressObj);
        // Start the progress polling:
        data.context.data('interval', setInterval(function () {
            $.get('progress.php', $.param([progressObj]), function (result) {
                // Trigger a fileupload progress event,
                // using the result as progress data:
                e = document.createEvent('Event');
                e.initEvent('progress', false, true);
                $.extend(e, result);
                $('#fileupload').data('fileupload')._onProgress(e, data);
            }, 'json');
        }, 1000)); // poll every second
    }
}).bind('fileuploadalways', function (e, data) {
    clearInterval(data.context.data('interval'));
});

progress.php

$s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
$progress = array(
        'lengthComputable' => true,
        'loaded' => $s['bytes_processed'],
        'total' => $s['content_length']
);
echo json_encode($progress);

Other Examples

Solution 2

This is my code its working fine Try it :

Demo URL (broken link)

http://codesolution.in/dev/jQuery/file_upload_with_progressbar/

Try this below code:

HTML:

<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }

.progress { 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>
</head>
<body>
    <h1>File Upload Progress Demo #1</h1>
    <code>&lt;input type="file" name="myfile"></code>
        <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadedfile"><br>
        <input type="submit" value="Upload File to Server">
    </form>

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

    <div id="status"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    complete: function(xhr) {
     bar.width("100%");
    percent.html("100%");
        status.html(xhr.responseText);
    }
}); 

})();       
</script>

</body>
</html>

upload.php :

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

Solution 3

May I suggest you FileDrop.

I used it to make a progess bar, and it's pretty easy.

The only downside I met, is some problems working with large amounts of data, because it dosen't seem to clear up old files -- can be fixed manually.

Not written as JQuery, but it's pretty nice anyway, and the author answers questions pretty fast.

Solution 4

While it may be good fun to write the code for a progress bar, why not choose an existing implementation. Andrew Valums wrote an excellent one and you can find it here:

http://fineuploader.com/

I use it in all my projects and it works like a charm.

Share:
25,363

Related videos on Youtube

Wasim A.
Author by

Wasim A.

[email protected] | Skype:wasimxe | Whatsapp: +923455407008

Updated on December 04, 2020

Comments

  • Wasim A.
    Wasim A. over 3 years
    <form enctype="multipart/form-data" action="upload.php" method="POST">
    <input name="uploaded" type="file" />
    <input type="submit" value="Upload" />
    </form>
    
    <?php
    if(isset($_REQUEST['submit'])){
       $target = "data/".basename( $_FILES['uploaded']['name']) ;
       move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
    }
    ?>
    

    I know Javascript, AJAX and JQuery etc very well and I believe an upload progress bar can be created using PHP, AJAX and Javascript etc.

    I am surprised how to get the size of upload (meaning each second I want to know, how much of the file is uploaded and how much is remaining, I think it should be possible using AJAX etc) file during upload is in process.

    Here is link to the PHP manual but I didn't understand that: http://php.net/manual/en/session.upload-progress.php

    Is there any other method to show the upload progress bar using PHP and AJAX but without use of any external extension of PHP? I don't have access to php.ini

  • Wasim A.
    Wasim A. over 12 years
    i know how to make changes to php.ini but problem is i don't have access to php.ini and i don't want to use Flash and even i can't upgrade php to latest version.
  • Niet the Dark Absol
    Niet the Dark Absol over 12 years
    If you can't have the right version of PHP for this, don't even bother trying to get it to work. It won't, end of story. This feature was only added in the latest PHP version.
  • Wasim A.
    Wasim A. over 12 years
    is there any method else than session.upload-progress i think before php 5.4 many of websites contain progress bar
  • Niet the Dark Absol
    Niet the Dark Absol over 12 years
    Those websites use other methods, typically Flash-based. Some newer browsers support some stuff about files, but I don't know too much about that.
  • EmeraldCoder
    EmeraldCoder over 11 years
    I use it too for some project. Work like a charm.
  • pattyd
    pattyd about 11 years
    I know this answer is old, so please excuse me, but don't you have to pay for fineuploader?
  • Joram van den Boezem
    Joram van den Boezem about 11 years
    The source is available under a GNU GPL v3 license here: github.com/Widen/fine-uploader
  • JuliSmz
    JuliSmz over 4 years
    uploadProgress is not an ajax option, but you can use this instead: stackoverflow.com/questions/42216409/…
  • ashleedawg
    ashleedawg over 3 years
    doesn't work for me. Also, links are outdated