Javascript check file size

前端 未结 4 1636
时光取名叫无心
时光取名叫无心 2021-01-12 22:33

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 tru

4条回答
  •  广开言路
    2021-01-12 22:59

    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.

提交回复
热议问题