反应-检查用户选择图像的尺寸

时间:2019-10-19 23:01:03

标签: reactjs image validation image-uploading

我有一个文件选择器,该选择器调用functin在将图像发送到服务器进行服务器端处理之前先对其进行验证。我试图确保上传的图像是pngjpg并且在2mb下。我还试图确保其尺寸不超过200 by 200。我能够成功检查文件类型和大小,但无法获取尺寸。

这是我的代码:

profilePicInputChange(event){

  var pattern = /^[\w,\s-]+\.[A-Za-z]{3}$/;

  var filepath = event.target.value.split("\\");
  var filename = filepath.pop();

  if(pattern.test(filename)){

    var extensionList = filename.split(".");
    var extension = extensionList.pop();

    if(extension === 'png' || extension === 'jpg'){
      if(event.target.files[0].size <= 2000000){
        document.getElementById("invalidLicence").innerHTML = "";
        this.setState({
          profilePic: event.target.files[0],
          profilePicValid: true
        });
      }else{
        document.getElementById("invalidProfilePic").innerHTML = "<strong>Please Upload a file less than 2MB.</strong>";
        document.getElementById("invalidProfilePic").style.color = "red";
        this.setState({
          profilePicValid: false
        });
      }
    }else{
      document.getElementById("invalidProfilePic").innerHTML = "<strong>Please Upload a valid file type.</strong>";
      document.getElementById("invalidProfilePic").style.color = "red";
      this.setState({
        profilePicValid: false
      });
    }
  }else{
    document.getElementById("invalidProfilePic").innerHTML = "<strong>Please Upload a file with a valid name.</strong>";
    document.getElementById("invalidProfilePic").style.color = "red";
    this.setState({
      profilePicValid: false
    });
  }
}

编辑1

也许本来应该提到这个,但是我尝试了这个问题的答案,但没有得到想要的结果:

  

Is it possible to check dimensions of image before uploading?

0 个答案:

没有答案