如何禁止向文件输入添加大文件

wil*_*007 1 jquery

我有输入文件

<input class="input-file" type=file/>
Run Code Online (Sandbox Code Playgroud)

我使用以下函数来检查文件大小

    $(".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();
    });
Run Code Online (Sandbox Code Playgroud)

问题是即使提示用户提示警告消息"图像太大.只能上传小于2MB的图像.",但最终MyBigFile.txt被添加到输入文件中.如何不让用户将大于2MB的文件添加到文件输入?

Mus*_*usa 5

您可以使用全新的输入替换有问题的输入,因为您无法对文件输入做很多事情.

$(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;
    }
});
Run Code Online (Sandbox Code Playgroud)

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