验证图片上传

时间:2015-11-17 09:28:23

标签: javascript jquery validation

我正在尝试在上传之前验证图片。我限制大小和像素,但问题是我仍然可以上传图像,即使它不适用于限制。如何使用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;
            }
        };
    }
  }


});

2 个答案:

答案 0 :(得分:0)

如果验证失败,您可以重置文件输入元素的值

var myFile = document.getElementById('file');
...
myFile.value=""

然后在页面中向用户显示验证。

答案 1 :(得分:0)

这是我作为替代方案所做的。直到我发现这一点,我才知道这是可能的。您只需将其添加到相关警报/返回false部分,它将禁用提交按钮。

jQuery("input[type='submit']").attr("disabled", 'disabled');