Basically, I want to figure out whether I should download a file using AJAX, depending on how large the filesize is.
I guess this question could also be rephrased as: How do I get only the header of an ajax request?
EDIT: ultima-rat0 in the comments told me of two questions that had already been asked that apparently are the same as this one. They are very similar, but they both want jQuery. I want a non-jQuery solution to this.
We can use FileChannel size() method to get file size in bytes.
sizeOf() Method. The class provides the sizeOf() method to get the file size in bytes. Syntax: public static long sizeOf(File file)
To get the file size, we will use filesize() function. The filesize() function returns the size of a file in bytes. This function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With