在 JavaScript 中按宽度和高度验证上传的文件

问题描述 投票:0回答:1

这段代码运行良好。它在上传之前限制图像的类型和大小,但此外,我想在上传之前限制图像的最大尺寸宽度和高度。如果宽度和高度不正确,我想限制上传,就像下面的脚本对扩展名和大小所做的那样。谢谢!

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">

javascript image validation upload
1个回答
1
投票

使用 clientWidthclientHeight 属性设置宽度和高度,然后应用您所需的条件。

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();
  
  // getting 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">

© www.soinside.com 2019 - 2024. All rights reserved.