我想在上传之前验证图片。我限制了尺寸和像素,但问题是我仍然可以上传图像,即使它不适用于限制。如何通过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