Ajax - 下载前获取文件大小

Ajax - Get size of file before downloading(Ajax - 下载前获取文件大小)
本文介绍了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 - 下载前获取文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)