Secure Image Upload Script

<!-- Input -->
<input type="file" name="image" accept="image/x-png,image/gif,image/jpeg" id="file" onchange="return fileValidation()" required>
<!-- Image preview -->
<div  id="imagePreview"></div>

<!-- Script -->
<script type="text/javascript">
function fileValidation(){
  var fileInput = document.getElementById('file');
  var filePath = fileInput.value;
  var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
  //Image extensions
  if(!allowedExtensions.exec(filePath)){
      alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
      fileInput.value = '';
      return false;
  }
      //Image Size
else if(fileInput.files[0].size > 1000000){
   alert("File is too big! Max Upload Size: 1 MB !");
   fileInput.value = "";
}
  else{
      //Image preview
      if (fileInput.files && fileInput.files[0]) {
          var reader = new FileReader();
          reader.onload = function(e) {
              document.getElementById('imagePreview').innerHTML = '<img class="card-img-top" src="'+e.target.result+'"/>';
          };
          reader.readAsDataURL(fileInput.files[0]);
      }
  }
}
</script>

    No comments found

    There are no comments on this page, sorry.

WebBeer - Beer & Code | Product Hunt Embed