Ajax - Get size of file before downloading
You can get XHR response header data manually:
http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
This function will get the filesize of the requested URL:
function get_filesize(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, true); // Notice "HEAD" instead of "GET",
// to get only the header
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(xhr.getResponseHeader("Content-Length")));
}
};
xhr.send();
}
get_filesize("http://example.com/foo.exe", function(size) {
alert("The size of foo.exe is: " + size + " bytes.");
});
Sometimes HEAD can act differently than GET so I suggest something like this that aborts the request after getting Content-Length
header:
new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/a.bin', true);
xhr.onreadystatechange = () => {
resolve(+xhr.getResponseHeader("Content-Length"));
xhr.abort();
};
xhr.send();
}).then(console.log);
If HEAD request is not possible:
The solution Ebrahim did only not work in firefox for me because context-length was not available for aborted request in firefox. So I used 'onprogress' event instead of 'onreadystatechange' event:
new Promise(
(resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onprogress = (event) => {
if (event.lengthComputable) {
resolve(event.total);
} else {
reject(new Error('No content-length available'));
}
xhr.abort();
};
xhr.send();
}
);