我想在上傳之前驗證圖片。我限制了尺寸和像素,但問題是我仍然可以上傳圖像,即使它不適用於限制。如何通過onchange
命令完成此驗證,從而阻止用戶或禁用上載。正在驗證圖片上傳
var myFile = document.getElementById('file');
myFile.addEventListener('change', function() {
image = new Image();
if(this.files[0].size > 800000)
{
alert("File size too big. Please upload a smaller image");
return false;
}
else
{
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(this.files[0]);
reader.onload = function (e)
{
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
image.onload = function() {
//Determine the Height and Width.
var height = this.height;
var width = this.width;
if (height > 500 || width > 375) {
alert("Height and Width must not exceed 500px(h) and 375px(w).");
return false;
}
else
{
alert("Uploaded image has valid Height and Width.");
return true;
}
};
}
}
});
它只在文件大小太大時上傳? – Ionut
更新了片段。 – Muppet