在javascript中验证图像尺寸

时间:2019-02-27 10:54:34

标签: javascript

我正在尝试使用更改事件从表单检查图像的尺寸,我可以成功地验证扩展名和大小,但是卡在尺寸验证中

<input type="file" name="files[]" onchange="validatePassport()" id="passportpic" required/> 

JavaScript

function validatePassport() {
            var formData = new FormData();

            var file = document.getElementById("passportpic").files[0];

            formData.append("Filedata", file);
            var t = file.type.split('/').pop().toLowerCase();
            if (t != "jpeg" && t != "jpg" && t != "png") {
                alert('Please select a valid image file');
                document.getElementById("passportpic").value = '';
                return false;
            }
              if(file.height > 200  || file.width  > 200) {
                alert("Height and Width must not exceed 200px.");
                document.getElementById("passportpic").value = '';
                return false;
              }
            if (file.size > 209715) {
                alert("Max Upload size is 200kb only");
                document.getElementById("passportpic").value = '';
                return false;
            }

            return true;
        }

1 个答案:

答案 0 :(得分:1)

您无法从文件对象中获得文件对象的图像宽度/高度。

您可以尝试类似的方法:

function validatePassport() {
    var formData = new FormData();

    var file = document.getElementById("passportpic").files[0];

    formData.append("Filedata", file);
    var t = file.type.split('/').pop().toLowerCase();
    if (t != "jpeg" && t != "jpg" && t != "png") {
        alert('Please select a valid image file');
        document.getElementById("passportpic").value = '';
        return false;
    }
    if (file.size > 209715) {
        alert("Max Upload size is 200kb only");
        document.getElementById("passportpic").value = '';
        return false;
    }

    // Now you have to check dimension
    var image = new Image();
    image.onload = function () {
        var imageWidth = this.width;
        var imageHeight = this.height;
        if(imageHeight > 200  || imageWidth > 200) { 
            alert("Height and Width must not exceed 200px.");
            document.getElementById("passportpic").value = '';
        }
    }

    var URLObject = window.URL || window.webkitURL;
    image.src = URLObject.createObjectURL(file);
    return true;
}