Javascript检查文件大小 [英] Javascript check file size

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

问题描述

如果网络服务器上文件的文件大小,是否可以继续使用javascript进行检查(例如 http:/ /www.mysite.com/myfile.js )大于0字节,如果是,则返回true或false值?

Is it possible to keep checking with javascript if the filesize of a file on a webserver (e.g. http://www.mysite.com/myfile.js) is larger than 0 bytes and if so return a true or false value?

提前致谢!

推荐答案

从理论上讲,您可以使用XHR发出HTTP HEAD 请求和检查响应标头中的 Content-Length

Theoretically, you could use XHR to issue a HTTP HEAD request and check the Content-Length in the response headers.

A HEAD 请求与常规 GET 请求服务器不得返回实际内容。换句话说,服务器会回复您尝试 GET 资源时的标题,但随后停止并且不发送文件。

A HEAD request is identical to a regular GET request except the server MUST NOT return the actual content. In other words, the server replies with the headers it would have had you tried to GET the resource, but then stops and does not send the file.

然而,一些服务器响应 HEAD 请求 Content-Length 标头 0 ,无论文件的实际大小如何。其他人回复文件的大小。

However, some severs respond to a HEAD request with a Content-Length header of 0, regardless of the actual size of the file. Others respond with the size of the file.

为了实现这一点,你必须祈祷你的服务器将文件的实际大小返回到 HEAD 请求。

In order to accomplish this, you'll have to pray your server returns a file's actual size to a HEAD request.

如果确实如此,获得这个价值很容易

$.ajax('/myfile.js', {
    type: 'HEAD',
    success: function(d,r,xhr) {
       fileSize = xhr.getResponseHeader('Content-Length');
    }
});

请注意,JSFiddle的服务器始终返回 0 时我们 HEAD / ,即使 / 16916 字节。

Note that JSFiddle's server always returns 0 when we HEAD /, even though / is 16916 bytes.

还要注意jQuery的文档说关于HTTP请求类型选项:

Also note what jQuery's docs say about the HTTP request type option:


要求的类型(POST或GET),默认为得到。注意:此处也可以使用其他HTTP请求方法,例如PUT和DELETE,但并非所有浏览器都支持它们。

The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

我刚刚在IE 6-10,Firefox 3.6-7,Opera 9-11和Chrome中测试了这个小提琴,并且每个浏览器都正确发出了 HEAD 请求,所以我不会担心这种含糊不清的声明。更值得关注的是您的服务器如何响应。

I just tested this Fiddle in IE 6-10, Firefox 3.6-7, Opera 9-11, and Chrome, and every single browser correctly issued the HEAD request, so I wouldn't worry about that vague incompatibility statement. Of more concern is how your server responds.

这篇关于Javascript检查文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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