這段代碼運行良好。它在上傳前限制影像的型別和大小,但此外,我想在上傳前限制影像的最大尺寸寬度和高度。如果寬度和高度不正確,我想限制上傳,就像下面的腳本對擴展名和大小所做的那樣。謝謝!
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">
uj5u.com熱心網友回復:
對寬度和高度使用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">
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362330.html
標籤:javascript 图片 验证 上传
