Wednesday, February 22, 2017

File size and extension validation before upload in javascript

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.
 Full Code :

<div style="margin:0 auto; width:50% text-align:center">
<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>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#file").change(function () {
        if(fileExtValidate(this)) {
             if(fileSizeValidate(this)) {
                 showImg(this);
             }   
        }   
    });

// File extension validation, Add more extension you want to allow
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
// size 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;
                }
     }
 }

 // display img preview before upload.
function showImg(fdata) {
        if (fdata.files && fdata.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#img').attr('src', e.target.result);
            }

            reader.readAsDataURL(fdata.files[0]);
        }
    }
});
</script>

No comments:

Post a Comment