Reputation: 18525
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
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;
}
});
Upvotes: 7