Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get upload progress of individual files with XMLHttpRequest

I'm using XMLHttpRequest (with jQuery) to get the upload progress of multiple files. By adding a "progress" event listener to the XMLHttpRequest object I can get event.loaded and event.total. Those variables give me the loaded and total bytes of all the files combined.

What I'd like to do is get the progress of each individual file, but from what I can see that information isn't available with XMLHttpRequest. Is that true?

I don't think this is even necessary, but here's my code:

var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
    xhr.upload.addEventListener('progress', function(event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
            percent = Math.ceil(position / total * 100);
        }
        updateProgressBar(percent);
    }, false);
}
return xhr;

If I can accomplish this with XMLHttpRequest that would be great. Any info on this would be appreciated.

like image 731
Gavin Avatar asked Aug 01 '13 14:08

Gavin


1 Answers

This is what i use,

$.ajax({
    xhr: function () {
        myXhr = $.ajaxSettings.xhr();
        myXhr.addEventListener('progress', function (e) { }, false);
        if (myXhr.upload) {
            myXhr.upload.onprogress = function (e) {
                var completed = 0;
                if (e.lengthComputable) {
                    var done = e.position || e.loaded,
                        total = e.totalSize || e.total;
                    completed = Math.round((done / total * 1000) / 10);
                }
                console.log(completed); // Displays the completed percentage
            }
        }
        return myXhr;
    }
});
like image 162
Balaji Viswanath Avatar answered Sep 23 '22 18:09

Balaji Viswanath