在上传之前限制文件大小

在上传之前限制文件大小

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

问题描述

在PHP上,他们可以在上传后限制文件大小,但不能在上传之前。我使用进行表单发布,它支持图像文件发布。

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.

通过在客户端执行此操作,它会阻止那些从Pentax拍摄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.

推荐答案

这是我在一个非常相似的问题中回答的副本:

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规范的一部分,所以它只适用于现代浏览器(v10要求IE)和我添加了

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/

旧浏览器支持

请注意,旧浏览器将返回 null 前一个 this.files 调用的值,因此访问 this.files [0] 将引发异常,您应该在使用之前

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,在上传之前限制文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 07:20