How to check file input size with jQuery?(如何使用 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 检查文件输入大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 jQuery 检查文件输入大小?


- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01