Steven
Steven

Reputation: 25284

How to check the size of an uploaded file using jQuery and jQuery Validate plugin?

I want to implement the jQuery Validation on the client. When a user is going to upload a file, the Jquery will check the size of the file and if it exceeds the max size, a user can not upload the file. How to do it using jQuery or jQuery Validate plugin?

Upvotes: 0

Views: 3982

Answers (3)

Rob Johnston
Rob Johnston

Reputation: 879

And a mere seven years later... I have a pull request in to validate the max size of a file (or a collection of files). It's under code review right now. See https://github.com/jquery-validation/jquery-validation/pull/2087

Upvotes: 0

Mahesh Lad
Mahesh Lad

Reputation: 2055

Jquery validation plugin code

 $.validator.addMethod('filesize', function (value, element, arg) {
            var minsize=1000; // min 1kb
            if((value>minsize)&&(value<=arg)){
                return true;
            }else{
                return false;
            }
        });

        $("#myform" ).validate({
            rules: {
                file_upload:{
                    required:true,
                    accept:"application/pdf,image/jpeg,image/png",
                    filesize: 200000   //max size 200 kb
                }
            },messages: {
                file_upload:{
                    filesize:" file size must be less than 200 KB.",
                    accept:"Please upload .jpg or .png or .pdf file of notice.",
                    required:"Please upload file."
                }
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

Min 1 kb to max 200 kb file size and it is tested

Upvotes: 0

Svetlozar Angelov
Svetlozar Angelov

Reputation: 21660

You can't do it with JQuery. The problem is that javascript can not access the file system.

Here is something you can read about the subject - Using jQuery, Restricting File Size Before Uploading

Upvotes: 2

Related Questions