在 JavaScript 中按宽度和高度验证上传的文件
Validate uploaded files by width and height in 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">
此代码运行良好。它在上传前限制了图像的类型和大小,但另外,我想在上传前限制图像的最大尺寸宽度和高度。如果宽度和高度不正确,我想限制上传,就像下面的脚本对扩展和大小所做的那样。谢谢!
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">