I would like to use XHR object’s “progress” event to get the progress of download.
Here’s example code from MDN
var req = new XMLHttpRequest();
req.addEventListener("progress", updateProgress, false);
req.addEventListener("load", transferComplete, false);
req.addEventListener("error", transferFailed, false);
req.addEventListener("abort", transferCanceled, false);
req.open();
...
// progress on transfers from the server to the client (downloads)
function updateProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
...
} else {
// Unable to compute progress information since the total size is unknown
}
}
function transferComplete(evt) {
alert("The transfer is complete.");
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
I’ve written similar code, but lengthComputable field of the progress event turns out to be false. The loaded field is some finite value, but total is set to zero.
From the comment in the code example above, I can see that the browser doesn’t get enough information in the HTTP response to calculate a meaningful download progress.
What is the correct way to write the response to make this work? The response I see in my testing has Transfer-encoding: chunked and Content-Length: 8. I am generating it from Tornado Web server.
In the chunked transfer encoding, the total length of the response is not indicated by the server, and therefore not known to the client in advance.
You can try two things.
Content-Length. This is what the Progress Events specification requires. But I don’t know if/how this is possible with Tornado.Or, include total length in a custom response header like
X-Total-Length. Then, use code like this to determine your percentage: