william007
william007

Reputation: 18525

How to disallow adding of big file to file input

I have input file

<input class="input-file" type=file/>

I use the following function to check the file size

    $(".input-file[type=file]").change(function () {
        var file = this.files[0];
        if (file.size > 2*1024*1024) {
            alert("Too large Image. Only image smaller than 2MB can be uploaded.");
            return false;
        }
        $(".input-file[type=file]").submit();
    });

Problem is even though user are prompted with the alert message "Too large Image. Only image smaller than 2MB can be uploaded.", but eventually MyBigFile.txt is added to the input file. How to NOT letting the user add the file which is larger than 2MB to the file input?

Upvotes: 2

Views: 3456

Answers (1)

Musa
Musa

Reputation: 97672

You can replace the offending input with a brand new one, since you can't do much to a file input.

$(document).on("change", ".input-file[type=file]", function () {
    var file = this.files[0];
    if (file.size > 2*1024*1024) {
        alert("Too large Image. Only image smaller than 2MB can be uploaded.");
        $(this).replaceWith('<input class="input-file" type="file">');
        return false;
    }
});

http://jsfiddle.net/EuAy8/2/

Upvotes: 7

Related Questions