JQuery – Check file size and file type before upload using JQuery

File Upload, JQuery Check file type and File Size of the File Being Upload – Working Code Example for Firefox and Chrome

When you provide a form to the user to upload a file(s), It is always a better idea to made the necessary checks on the client side, on the front end, so that user do not upload any invalid files, malicious code or large files to your server. You can stop those files being uploaded on the server. Later, when the user submits the form with attachment files, you may recheck on the server side, just to be assured, that uploaded files are within size limit and in accepted file formats.

You may check the file formats and limit file size with Jquery. There are sample codes available on the different websites, that work either with Firefox or with Chrome browser but not with the both. The following code is working and tested with Firefox as well as with the Chrome browser.

Please note, this script actually DO NOT upload the file, It check the file type and file size on Front-End side with Jquery before it sends the file to the server. If you are using this code, do the necessary validation on server side too.

You may need to change the code, according to your need.

 

File Upload Form


<form id="frm_upload" class="form-horizontal" action="#" enctype="multipart/form-data" method="post">

<div class="col-sm-2">
<span style="padding-right: 20px;"><b>Attach:</b></span>
<label class="btn btn-default" for="upload_file">
<input id="upload_file" style="display: none;" name="upload_file" type="file" />Browse</label></div>



<div class="col-sm-7" style="margin: 4px;" align="right">
<button id="reset" class="btn btn-default" tabindex="4" type="reset">Cancel</button>
<button id="submit-form" class="btn btn-primary" tabindex="3" name="submit-form" type="submit">Submit</button>
</div>

</form>

JQuery Code


<script>
$('input[type=file]').change(function(){
var ext = $('#upload_file').val().split('.').pop().toLowerCase();
//Allowed file types
if($.inArray(ext, ['gif','png','jpg','jpeg', 'docx', 'doc', 'pdf', 'rtf', 'ppt', 'txt', 'odt']) == -1) {
alert('The file type is invalid!');
$('#upload_file').val("");
$('#upload-file-info').html("");
}

//Tested in Firefox and Google Chorme
sizee = $("#upload_file")[0].files[0].size; //file size in bytes
sizee = sizee / 1024; //file size in Kb
sizee = sizee / 1024; //file size in Mb

//file size more than 10Mb
if (sizee &gt; 10) {
alert("Maximum file size is 10Mb");
return false;
}  else {
//Ajax code to upload file to server
}
});
</script>

The above example code was written with Bootstrap 3.0 and Jquery, So you need to add the necessary CSS and JS files of Bootstrap and Jquery to make it working.

 

Leave a Reply

Your email address will not be published. Required fields are marked *