如何使用jQuery检查文件输入大小? [英] How to check file input size with jQuery?

查看:22
本文介绍了如何使用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

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

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