我有一个文件选择器,该选择器调用functin在将图像发送到服务器进行服务器端处理之前先对其进行验证。我试图确保上传的图像是png
或jpg
并且在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?