simple progress 'bar' for image upload -- immediately at 100%

时间:2015-07-31 19:32:16

标签: javascript php jquery file-upload progress

I am trying to add a simple progress bar/number to my PHP image upload. If javascript is enabled, this script shall work, but now, it immediatly shows 100%, before everything has been uploaded, and then it shows "images are beeing processed", also too early, I think.

Something must be wrong:

$('form#uploadform').submit(function(){
var formdata = $('form#uploadform').serialize();
$('p.isloading').show();

$.ajax({
xhr: function () {
    var xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            $('#uploadprogress').text(percentComplete * 100 + '%');
        }
    }, false);
    xhr.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            $('#uploadprogress').text(percentComplete * 100 + '%');
        }
    }, false);
    return xhr;
},
type: 'POST',
url: "/upload",
data: formdata,
success: function (data) { $('#uploadprogress').text('images are being processed'); }
});
//return false;
});

I want a simple way to show how much is already uploaded, but it seems I am doing it wrong. Any help is appreciated.

1 个答案:

答案 0 :(得分:0)

答案在@Amarnadh Meda提供的链接上。

JavaScript -

$(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) {
        status.html(xhr.responseText);
    }
});
}); 

HTML -

<form action="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>

编辑#1:

在这里找到类似的问题。 File upload progress bar with jQuery