Home > Net >  Validate uploaded files by width and height in JavaScript
Validate uploaded files by width and height in JavaScript

Time:11-21

This code is working well. It restricts the type and size of the image before upload but in addition, I would like to restrict the maximum dimension width and height of the image before upload. I would like to restrict the upload if the width and height are not correct like the script below did for extension and size. Thank you!

document.getElementById("files").addEventListener("change", validateFile)

function validateFile(){
  const allowedExtensions =  ['jpg'],
        sizeLimit = 150000; 
        

  const { name:fileName, size:fileSize } = this.files[0];

  const fileExtension = fileName.split(".").pop();
  

  if(!allowedExtensions.includes(fileExtension)){
    alert("This is not a valid image");
    this.value = null;
  }else if(fileSize > sizeLimit){
    alert("This is not a valid image")
    this.value = null;
  }
}
    <input onchange="validateFile()" type="file" id="files" class="box_file">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use clientWidth & clientHeight property for width and height and then apply your desired condition.

var img = document.getElementById('files');
img.addEventListener('change', function() {
    const allowedExtensions =  ['jpg'],
        sizeLimit = 150000;     

  const { name:fileName, size:fileSize } = this.files[0];

  const fileExtension = fileName.split(".").pop();
  
  //gettting height & width
    var width = img.clientWidth;
    var height = img.clientHeight;
  
  let alrt = "";

  if(!allowedExtensions.includes(fileExtension)){
    alrt  = "This is not a valid image! \n";
  }
  debugger;
  if(fileSize > sizeLimit){
    alrt  = "This is not a valid image! \n";
  }
  
  if(width != 200 && height != 20 ){ //checking height & width
        alrt  = "not a valid dimention! \n";
    }
    
    if(alrt){
     alert(alrt);
     img.value = null;
     return false;
    }
    else{
        alert("upload successful!");
        return true;
    }

});
<input type="file" id="files" class="box_file">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related