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 - 下载前获取文件大小


基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01