XMLHttpRequest and a progress bar?

8.4k views Asked by At

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

There are 1 answers

0
Ian Clark On

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