How to check file input size with jQuery?

前端 未结 8 2415
渐次进展
渐次进展 2020-11-22 09:21

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

8条回答
  •  悲&欢浪女
    2020-11-22 09:29

    If you want to use jQuery's validate you can by creating this method:

    $.validator.addMethod('filesize', function(value, element, param) {
        // param = size (en bytes) 
        // element = element to validate ()
        // 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" }
    });
    

提交回复
热议问题