【问题标题】:Validate uploaded files by width and height in JavaScript在 JavaScript 中按宽度和高度验证上传的文件
【发布时间】:2021-12-29 02:11:52
【问题描述】:

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

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】:

    使用clientWidth & clientHeight 属性作为宽度和高度,然后应用您想要的条件。

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

    【讨论】:

    • @Michael777 检查更新的代码,你的代码给了我错误,这就是为什么我改变了一点
    • @Michael777 我已经更新了一点代码,现在试试这个,告诉我它是否有效或给出错误
    • @Michael777 它显示了什么?如果有任何错误,您可以检查控制台吗?
    • @Michael777 抱歉,现在试试。以前是一步一步验证,现在全部验证,有什么不懂的随时问我,没问题
    • @Michael777 没问题!很乐意随时提供帮助。 ^_^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多