Download progress (with or without XMLHttpRequest 2) with Javascript

XMLHttpRequest 2has a new thing. It can upload files. I got this job (it is very easy). Now I am wondering if there is a way to get the download progress of this file. I would not be interested in this, but in Google Chrome (8) I saw that the onreadystatechange event is equal XMLHttpRequestProgressEvent. Progress ... There is nothing about the progress of the download (just the status of the request), but it made me think.

Google Chrome has a progress counter when downloading large files initially. This is the standard. He is always there and uncomfortable. It is in the status bar. Is there something similar with Javascript? I would like to add it to a good item <progress>or something else.

I don't want SWF or Java loaders (with polls and> JS callbacks). He must be native. If the browser can do this, nowadays Javascript should do it, right !? =)

In the absence XMLHttpRequest 2, I think it would be impossible with the most standard file upload (without ajax and just <input type=file>).

thanks for the info

+3
source share
1 answer

Capture the progress event. This will give you progress for all queries. First check if the download object is available - this will give you progress only for the download part.

Something like that:

var xhr; // this is your XMLHttpRequest

// hook to upload events if available, otherwise snag all progress events
var eventSource = xhr.upload || xhr;

eventSource.addEventListener("progress", function(e) {
    // normalize position attributes across XMLHttpRequest versions and browsers
    var position = e.position || e.loaded;
    var total = e.totalSize || e.total;

    // TODO: display progress
});
+9
source

Source: https://habr.com/ru/post/1779635/


All Articles