2015-11-17 44 views
1

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


}); 
+0

它只在文件大小太大时上传? – Ionut

+0

更新了片段。 – Muppet

回答

0

如果验证失败

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

可以重置文件输入元素的值,然后验证显示在页面的用户。

0

这是我做的替代方案。直到遇到这种情况,我才知道这是可能的。您只需将其添加到相关的警报/返回false部分,并禁用提交按钮。

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

建议您使用jQuery ['prop(..)'](http://api.jquery.com/prop)函数,例如jQuery(“input [type ='submit']”)。prop(“disabled”,true) –

+0

你可以给出一个简短的反馈答案,为什么?我有兴趣知道,因为我不知道它 – Muppet

+0

这已被覆盖在另一个[后](http://stackoverflow.com/questions/5874652/prop-vs-attr)它进入一些有关差异的详细信息。希望有所帮助。 –