使用 jQuery,在上传前限制文件大小 [英] Using jQuery, Restricting File Size Before Uploading

查看:43
本文介绍了使用 jQuery,在上传前限制文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 上,他们有一种方法可以在上传后限制文件大小,而不是在上传之前.我使用 Malsup jQuery Form Plugin 进行表单发布,它支持图像文件发布.

On PHP, they have a way to restrict file size AFTER uploading, but not BEFORE uploading. I use the Malsup jQuery Form Plugin for my form posting, and it supports image file posting.

我想知道是否有限制,我可以设置多少字节可以通过该 AJAX 流传递到服务器?这可以让我检查文件大小并在文件太大时返回错误.

I was wondering if perhaps there's a restriction where I can set how many bytes can pass through that AJAX stream up to the server? That could permit me to check that file size and return an error if the file is too big.

通过在客户端执行此操作,它会阻止那些从宾得拍摄 10MB 照片并尝试上传的新手.

By doing this on the client side, it blocks those newbies who take a 10MB photo shot from their Pentax and try to upload that.

推荐答案

这是我在一个非常相似的问题中的回答的副本:如何使用 jQuery 检查文件输入大小?

This is a copy from my answers in a very similar question: How to check file input size with jQuery?

您实际上无权访问文件系统(例如读取和写入本地文件).但是,由于 HTML5 文件 API 规范,您确实可以访问一些文件属性,文件大小就是其中之一.

You actually don't have access to the filesystem (for example reading and writing local files). However, due to the 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-文件大小/

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天全站免登陆