2013-07-02 102 views
13

基本上,我想知道是否应该使用AJAX下载文件,具体取决于文件大小。Ajax - 下载前获取文件大小

我想这个问题也可以改写为:我如何只获取ajax请求的标题?


编辑ultima-rat0在评论中告诉我的那些已经被问,显然是相同的,因为这一个两个问题。他们非常相似,但他们都希望jQuery。我想要一个非jQuery解决方案。

+2

可能重复? http://stackoverflow.com/questions/1484303/get-size-of-file-requested-via-ajax和http://stackoverflow.com/questions/1440723/find-size-of-file-behind-download- link-with-jquery –

+0

@ ultima_rat0谢谢,出于某种原因,他们没有出现在stackexchange的重复列表中......不知道为什么。那是_only_下载头文件吗? – MiJyn

+1

你可以手动获得XHR-respone数据:http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method – hungdoan

回答

21

您可以手动得到XHR响应头数据:

http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method

此功能将得到请求的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."); 
}); 
+0

如果我使用变量而不是警报?为什么他们返回'未定义'?我如何在变量中存储'xhr.getResponseHeader(“Content-Length”)'? –

+0

@FabioCalvosa xhr.open(“HEAD”,url,true);''//'false'使得请求异步 所以当你调用这样的函数时: var myVar; get_filesize('https://sample.com'); alert(myVar); //你的变量是'undefined' 但是如果你像这样改变你的代码: var myVar; get_filesize('https://sample.com',function(){ alert(myVar); //你的变量不会'未定义'因为你调用了'回拨'方法 }); – hungdoan

+0

如果浏览器和服务器执行gzip编码,这将永远不会工作...内容长度标头被禁止。更糟糕的是,W3C/xhr禁止接受编码的设置,从而消除了客户端解决方案的任何希望......非常令人沮丧 – user3338098

0

有时头可采取不同的比GET所以我建议像这样在取得Content-Length后中止请求标题:

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