File Upload Progress Demo (cors)


0%

Markup

<form 
    action="http://malsup.com/jquery/form/file-echo2.php" 
    method="post" 
    enctype="multipart/form-data">

    <input type="file" name="myfile"><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>

Client Script

<script>
(function() {
"use strict";

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);
    },
    success: function(data, statusText, xhr) {
        var percentVal = '100%';
        bar.width(percentVal);
        percent.html(percentVal);
        status.html(xhr.responseText);
    },
    error: function(xhr, statusText, err) {
        status.html(err || statusText);
    }
}); 

})();       
</script>

Server Script (file-echo2.php)

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

foreach($_FILES as $file) {
    $n = $file['name'];
    $s = $file['size'];
    if (is_array($n)) {
        $c = count($n);
        for ($i=0; $i < $c; $i++) {
            echo "<br>uploaded: " . $n[$i] . " (" . $s[$i] . " bytes)";
        }
    }
    else {
        echo "<br>uploaded: $n ($s bytes)";
    }
}
?>