Reputation: 2798
I would like to attach an event to all the input type="file" on my website to check if the file size is superior to 5mo, and if so block the upload and display a warning instead. Is it possible?
Upvotes: 1
Views: 3391
Reputation: 159
You can just bind the change event with jQuery:
$('input[type="file"]').change(function(){
var f=this.files[0];
var sizeInMb = f.size/1024;
var sizeLimit= 1024*5; // if you want 5 MB
if (sizeInMb > sizeLimit) {
alert('Sorry the file exceeds the maximum size of 5 MB!');
// reset the input (code for all browser)
this.replaceWith(input.val('').clone(true));
return false;
}
else {
// go on
}
}
Hope this helps.
Upvotes: 3
Reputation: 29693
you can try as below:
HTML
<input type="file" id="myFile" />
<span class="err"></span>
JS
$('#myFile').on('change', function(e) {
if((this.files[0].size/1000) > 5120)
{
$('.err').text('File size limit exceeded');
e.preventDefault();
}
else
$('.err').text('');
});
Upvotes: 0