Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest and a progress bar?

I send a series of images and data using formData and an XMLHttpRequest, which uploads the data to a database and the images to S3.

The problem I'm having though is the progress bar jumps to 100% straight away.

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/gateway/add');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onload = function () {
        };
        xhr.upload.onprogress = function (event){

            if(event.lengthComputable){
                var complete = (event.loaded / event.total * 100 | 0);
                $('.meter').css('width', complete+'%');
            }
        };

        xhr.send(formData);
like image 753
panthro Avatar asked Jul 10 '26 16:07

panthro


1 Answers

It works for me, my guess is you're not doing something else correctly. Note that I've changed to addEventListener because I think that's better practice, but apart from that it's basically your code:

$("#in").on("change", function (e) {
    var file = this.files[0],
        formData = new FormData(),
        xhr = new XMLHttpRequest();

    formData.append('files', file);

    xhr.open('POST', '');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.upload.addEventListener("load", function () {
        $(".meter").addClass("done");
    });
    xhr.upload.addEventListener("progress", function (event) {
        if (event.lengthComputable) {
            var complete = (event.loaded / event.total * 100 | 0);
            $('.meter').css('width', complete + '%');
        }
    });

    xhr.send(formData);
    return false;
});
like image 96
Ian Clark Avatar answered Jul 13 '26 11:07

Ian Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!