JavaScript file upload size validation

后端 未结 13 2176
眼角桃花
眼角桃花 2020-11-22 00:23

Is there any way to check file size before uploading it using JavaScript?

13条回答
  •  难免孤独
    2020-11-22 01:08

    If you're using jQuery Validation, you could write something like this:

    $.validator.addMethod(
        "maxfilesize",
        function (value, element) {
            if (this.optional(element) || ! element.files || ! element.files[0]) {
                return true;
            } else {
                return element.files[0].size <= 1024 * 1024 * 2;
            }
        },
        'The file size can not exceed 2MB.'
    );
    

提交回复
热议问题