如何使用 jQuery 检查文件输入大小?
我有一个具有文件上传功能的表单,如果用户尝试上传的文件太大,我希望能够有一些很好的客户端错误报告,有没有办法使用 jQuery 检查文件大小,要么纯粹在客户端上,要么以某种方式将文件发回服务器进行检查?
I have a form with file upload capabilities and I would like to be able to have some nice client side error reporting if the file the user is trying to upload is too big, is there a way to check against file size with jQuery, either purely on the client or somehow posting the file back to the server to check?
推荐答案
你实际上没有访问文件系统的权限(例如读写本地文件),但是由于 HTML5 File Api 规范,有一些文件属性您确实有权访问,文件大小就是其中之一.
You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.
对于下面的 HTML
<input type="file" id="myFile" />
尝试以下方法:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
由于它是 HTML5 规范的一部分,它只适用于现代浏览器(IE 需要 v10),我添加了 这里 更多细节和你应该知道的其他文件信息的链接:http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-文件大小/
As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/
旧浏览器支持
请注意,旧浏览器将为之前的 this.files
调用返回 null
值,因此访问 this.files[0]
将引发异常,您应该在使用前检查文件 API 支持
Be aware that old browsers will return a null
value for the previous this.files
call, so accessing this.files[0]
will raise an exception and you should check for File API support before using it
相关文章