Ajax - 下载前获取文件大小 [英] Ajax - Get size of file before downloading

查看:570
本文介绍了Ajax - 下载前获取文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically, I want to figure out whether I should download a file using AJAX, depending on how large the filesize is.

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

I guess this question could also be rephrased as: How do I get only the header of an ajax request?

编辑:<评论中的一个问题告诉了我两个已经被问过的问题,显然与这个问题是一样的.href =https://tackoverflow.com/users/2399627/ultima-rat0> 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 - 下载前获取文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆