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



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

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

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

相关内容

  • 没有找到相关文章

最新更新