It is a good idea to apply quick client side validation on file / image upload in javaScript, You can easily check file extension and size before file upload, So that user won’t be allow to upload garbage and large size of files. And this is good approach to maintain good server health to prevent garbage files.
In my last tutorial we talked about how to display image preview before upload, Like same in this tutorial we’ll again use HTML File Api to get files details from client’s browsers.
HTML
Here is the some demo html with file input box.
<form id="form"> <input type='file' id="file" /> <br/> <span style="color:red"> Note: Please select only image file (eg: .png, .jpeg, .jpg, .gif etc)<br/> Max File size : 1MB allowed span><br/> <img id="img" src="http://placehold.it/200x200" alt="No image uploaded" /> form> |
JavaScript + Jquery
Below I have created individually function for file extension and size validation, Here i validated image extension , for example image extension should be .png, .jpg, .jpeg, or .gif etc, other file extensions are not allowed, You can add more extensions on validExt variable.
Image extension validation before upload
var validExt = ".png, .gif, .jpeg, .jpg"; function fileExtValidate(fdata) { var filePath = fdata.value; var getFileExt = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase(); var pos = validExt.indexOf(getFileExt); if(pos < 0) { alert("This file is not allowed, please upload valid file."); return false; } else { return true; } } |
File size validation before upload
following function will get the file size and validate your maximum allowed size, you can set your max file size limit just assign file size to maxSize variable in kb
var maxSize = '1024'; function fileSizeValidate(fdata) { if (fdata.files && fdata.files[0]) { var fsize = fdata.files[0].size/1024; if(fsize > maxSize) { alert('Maximum file size exceed, This file size is: ' + fsize + "KB"); return false; } else { return true; } } } |
Finally call all the functions on file input .change event and pass file data to validate one by one.
$("#file").change(function () { if(fileExtValidate(this)) { if(fileSizeValidate(this)) { showImg(this); } } }); |
See live demo and download source code..