Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax - Get size of file before downloading

Tags:

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.

like image 722
MiJyn Avatar asked Jul 02 '13 01:07

MiJyn


People also ask

How to get file size in bytes java?

We can use FileChannel size() method to get file size in bytes.

How to get file size using java?

sizeOf() Method. The class provides the sizeOf() method to get the file size in bytes. Syntax: public static long sizeOf(File file)

How to get file size using php?

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.


2 Answers

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."); }); 
like image 84
Hung Doan Avatar answered Nov 05 '22 14:11

Hung Doan


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); 
like image 33
Ebrahim Byagowi Avatar answered Nov 05 '22 13:11

Ebrahim Byagowi