Ajax - Get size of file before downloading

后端 未结 4 2021
孤街浪徒
孤街浪徒 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条回答
  •  猫巷女王i
    2020-12-05 08:25

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

提交回复
热议问题