Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check file size

Is it possible to keep checking with javascript if the filesize of a file on a webserver (e.g. http://www.mysite.com/myfile.js) is larger than 0 bytes and if so return a true or false value?

Thanks in advance!

like image 709
Ben Paton Avatar asked Oct 26 '11 22:10

Ben Paton


1 Answers

Theoretically, you could use XHR to issue a HTTP HEAD request and check the Content-Length in the response headers.

A HEAD request is identical to a regular GET request except the server MUST NOT return the actual content. In other words, the server replies with the headers it would have had you tried to GET the resource, but then stops and does not send the file.

However, some severs respond to a HEAD request with a Content-Length header of 0, regardless of the actual size of the file. Others respond with the size of the file.

In order to accomplish this, you'll have to pray your server returns a file's actual size to a HEAD request.

If it does, getting that value is easy:

$.ajax('/myfile.js', {
    type: 'HEAD',
    success: function(d,r,xhr) {
       fileSize = xhr.getResponseHeader('Content-Length');
    }
});

Note that JSFiddle's server always returns 0 when we HEAD /, even though / is 16916 bytes.

Also note what jQuery's docs say about the HTTP request type option:

The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

I just tested this Fiddle in IE 6-10, Firefox 3.6-7, Opera 9-11, and Chrome, and every single browser correctly issued the HEAD request, so I wouldn't worry about that vague incompatibility statement. Of more concern is how your server responds.

like image 135
josh3736 Avatar answered Sep 20 '22 22:09

josh3736