Ajax - Get size of file before downloading

后端 未结 4 1982
孤街浪徒
孤街浪徒 2020-12-05 07:39

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

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 08:17

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

提交回复
热议问题