简体   繁体   English

如何使用 jQuery 检查文件输入大小?

[英]How to check file input size with 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?我有一个具有文件上传功能的表单,如果用户尝试上传的文件太大,我希望能够有一些不错的客户端错误报告,有没有办法用 jQuery 检查文件大小,或者纯粹在客户端或以某种方式将文件发回服务器进行检查?

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. 您实际上没有访问文件系统的权限(例如,读取和写入本地文件),但是,由于HTML5 File Api规范,您确实可以访问某些文件属性,并且文件大小是其中之一。

For the HTML below 对于下面的HTML

<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/ 由于它是HTML5规范的一部分,因此仅适用于现代浏览器(IE需要v10),我在此处添加更多详细信息以及您应该了解的其他文件信息的链接: http : //felipe.sabino.me/javascript / 2012/01/30 / javascipt-检查文件大小/


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 请注意,旧的浏览器将为之前的this.files调用返回null值,因此访问this.files[0]将引发异常,您应该在使用前检查File API支持。

If you want to use jQuery's validate you can by creating this method: 如果要使用jQuery的validate ,可以通过创建以下方法:

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 
});

You would use it: 您将使用它:

$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

This code: 这段代码:

$("#yourFileInput")[0].files[0].size;

Returns the file size for an form input. 返回表单输入的文件大小。

On FF 3.6 and later this code should be: 在FF 3.6及更高版本上,此代码应为:

$("#yourFileInput")[0].files[0].fileSize;

I am posting my solution too, used for an ASP.NET FileUpload control. 我也发布了用于ASP.NET FileUpload控件的解决方案。 Perhaps someone will find it useful. 也许有人会发现它有用。

    $(function () {        
    $('<%= fileUploadCV.ClientID %>').change(function () {

        //because this is single file upload I use only first index
        var f = this.files[0]

        //here I CHECK if the FILE SIZE is bigger than 8 MB (numbers below are in bytes)
        if (f.size > 8388608 || f.fileSize > 8388608)
        {
           //show an alert to the user
           alert("Allowed file size exceeded. (Max. 8 MB)")

           //reset file upload control
           this.value = null;
        }
    })
});

Use below to check file's size and clear if it's greater, 在下面使用以下命令检查文件的大小,并清除文件大小是否较大,

    $("input[type='file']").on("change", function () {
     if(this.files[0].size > 2000000) {
       alert("Please upload file less than 2MB. Thanks!!");
       $(this).val('');
     }
    });

You can do this type of checking with Flash or Silverlight but not Javascript. 您可以使用Flash或Silverlight进行此类检查,但不能使用Javascript。 The javascript sandbox does not allow access to the file system. javascript沙箱不允许访问文件系统。 The size check would need to be done server side after it has been uploaded. 上载后,需要在服务器端进行大小检查。

If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. 如果要使用Silverlight / Flash路线,则可以检查是否未默认将它们安装为使用常规控件的常规文件上传处理程序。 This way, if the do have Silverlight/Flash installed their experience will be a bit more rich. 这样,如果确实安装了Silverlight / Flash,他们的经验将更加丰富。

<form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
</form>
<button onclick="checkSize();"></button>
<script>
    function checkSize(){
        var size = $('#uploadForm')["0"].firstChild.files["0"].size;
        console.log(size);
    }
</script>

I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything. 如果您不打算通过标准的ajax / html5方法提交表单,我发现这是最简单的方法,但是当然可以使用任何方法。

NOTES: 笔记:

var size = $('#uploadForm')["0"]["0"].files["0"].size;

This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). 这曾经可以工作,但现在不再适用于chrome,我只是测试了上面的代码,它同时适用于ff和chrome(最新)。 The second ["0"] is now firstChild. 第二个[“ 0”]现在是firstChild。

Plese try this: 请尝试以下操作:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

HTML code: HTML 代码:

<input type="file" id="upload" class="filestyle" onchange="SizeCheck();"/>

JavaScript Function: JavaScript Function:

function SizeCheck() {
            var fileInput = document.getElementById('upload').files;
            var fsize = fileInput[0].size;
            var file = Math.round((fsize / 1024));
            if (file >= 10240) {     //10MB
               //Add Alert Here If 
                $('#upload_error').html("* File Size < 10MB");
            }
            else {
                $('#invoice_error').html("");
            }
        }
<script>
if (Math.round((document.getElementById('Your_input_id').files[0].size / 1024)>= 1024) { //2MB
$("#your_error_id").html("File Size < 1MB");
$("#your_error_id").css("color", "#dd4b39");
$("#Your_input_id").val('');
return false;
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM