Ajax - Get size of file before downloading(Ajax - 下载前获取文件大小)
问题描述
基本上,我想根据文件大小确定是否应该使用 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 - 下载前获取文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Ajax - 下载前获取文件大小


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01