如何检查与jQuery的文件输入大小? [英] How to check file input size with jQuery?
问题描述
我有一个文件上传功能的表单,我希望能够有一些很好的客户端错误报告,如果用户试图上传的文件太大了,有没有一种方法来检查与jQuery的文件大小,无论是纯粹在客户端或以某种方式张贴文件回服务器检查?
您实际上没有访问到文件系统(例如读写本地文件),但是,由于HTML5文件Api规范,有一些文件属性,你有权访问,文件大小是其中之一。
对于下面的HTML
< input type =fileid =myFile/> ;
请尝试以下操作:
//绑定到输入字段的onchange事件
$('#myFile')。bind('change',function(){
// this .files [0] .size获取文件的大小。
alert(this.files [0] .size);
});因为它是HTML5规范的一部分,所以它只适用于现代浏览器(v10需要的版本)。 IE),我在这里添加了 有关其他文件信息的更多细节和链接,你应该知道: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/
旧浏览器支持
请注意,旧浏览器将返回 null 值为前面 this.files
调用,所以访问 this.files [0]
将引发异常,您应该在使用之前检查File API支持
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?
解决方案 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.
For the HTML below
<input type="file" id="myFile" />
try the following:
//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);
});
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/
Old browsers support
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
这篇关于如何检查与jQuery的文件输入大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!