问题描述
基本上,我想根据文件大小确定是否应该使用 AJAX 下载文件.
Basically, I want to figure out whether I should download a file using AJAX, depending on how large the filesize is.
我想这个问题也可以改写为:如何只获取 ajax 请求的标头?
I guess this question could also be rephrased as: How do I get only the header of an ajax request?
编辑:ultima-rat0 在评论中告诉我两个问题已经被问过了,显然和这个一样.它们非常相似,但它们都想要 jQuery.我想要一个非 jQuery 解决方案.
EDIT: ultima-rat0 in the comments told me of two questions that had already been asked that apparently are the same as this one. They are very similar, but they both want jQuery. I want a non-jQuery solution to this.
推荐答案
可以手动获取XHR响应头数据:
You can get XHR response header data manually:
http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-方法
此函数将获取请求的 URL 的文件大小:
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.");
});
这篇关于Ajax - 下载前获取文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!