Check File Size & Extension Before Uploading Using jQuery

Check File Size & Extension Before Uploading Using jQuery

by Akram kamal

HTML

<form name="form" method="post" action="" enctype="multipart/form-data" > 
<p><label>Upload Picture:</label> <input type="file" name="file" id="picture" required /></p>
<p id="pic_error1" style="display:none; color:#FF0000;">Image formats should be JPG, JPEG, PNG or GIF.</p>
<p id="pic_error2" style="display:none; color:#FF0000;">Max file size should be 1MB.</p>
<p><label>Upload Signature:</label> <input type="file" name="file1" id="signature" required /></p>
<p id="sig_error1" style="display:none; color:#FF0000;">Image formats should be JPG, JPEG, PNG or GIF.</p>
<p id="sig_error2" style="display:none; color:#FF0000;">Max file size should be 1MB.</p>
<p><input name="submit" type="submit" value="Submit" id="submit" /></p>
</form>

JavaScript

$('input[type="submit"]').prop("disabled", true);
var a=0;
var b=0;
//binds to onchange event of your input field
$('#picture').bind('change', function() {
if ($('input:submit').attr('disabled',false)) {$('input:submit').attr('disabled',true);}	
var ext = $('#picture').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
    { $('#pic_error1').slideDown("slow"); $('#pic_error2').slideUp("slow"); a=0;} else { 
    var picsize = (this.files[0].size);
    if (picsize > 1000000)
    { $('#pic_error2').slideDown("slow"); a=0;} else { a=1; $('#pic_error2').slideUp("slow"); }
$('#pic_error1').slideUp("slow");
if (a==1 && b==2) {$('input:submit').attr('disabled',false);}
}
});

$('#signature').bind('change', function() {
if ($('input:submit').attr('disabled',false)) {$('input:submit').attr('disabled',true);}	
  var ext = $('#signature').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
    { $('#sig_error1').slideDown("slow"); $('#sig_error2').slideUp("slow"); b=0;} else { 
    var picsize = (this.files[0].size);
    if (picsize > 1000000)
    { $('#sig_error2').slideDown("slow"); b=0;} else { b=2; $('#sig_error2').slideUp("slow"); }
$('#sig_error1').slideUp("slow"); 
if (a==1 && b==2) {$('input:submit').attr('disabled',false);}
}
});