Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  106] [ 5]  / answers: 1 / hits: 25820  / 11 Years ago, tue, july 2, 2013, 12:00:00

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.


More From » ajax

 Answers
7

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.);
});

[#77268] Sunday, June 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alvin

Total Points: 55
Total Questions: 101
Total Answers: 109

Location: Sudan
Member since Tue, Aug 3, 2021
3 Years ago
;