2017-06-22 127 views
0

我試圖限制上傳不符合我們規範的圖像的能力。它似乎工作的大部分,但是,我似乎無法找到一種方法來停止(或刪除),如果它是無效的實際上傳。我在jquery中不太強大,所以我可能錯過了一些東西。任何幫助,將不勝感激。限制按尺寸和尺寸上傳無效圖像

演示:http://jsfiddle.net/46yuaqLm/2/

HTML:<input type="file" id="file" />

的Javascript:

var _URL = window.URL || window.webkitURL; 

$("#file").change(function(e) { 
    var file, img; 
     var iSize = ($("#file")[0].files[0].size/1000); 


    if ((file = this.files[0])) { 
     img = new Image(); 
     img.onload = function() { 
      if(this.width !== 300 && this.height !== 300 || iSize >= 500){ 
      alert("Image needs to be 300x300px. The submitted file was "+this.width + "x" + this.height + "px and " + iSize + "kb." + "Please try a different image."); 
      img.src = _URL.createObjectURL(file); 

      } else { 
      alert(this.width + "x" + this.height + "px and "+ iSize +"kb. Your image meet the requirements"); 

      } 
     }; 
     img.onerror = function() { 
      alert("not a valid file: " + file.type); 
     }; 

    } 

}); 

回答

1

$(function() { 
 
     var _URL = window.URL || window.webkitURL; 
 
     $("#file").change(function (e) { 
 
      var self = $(this); 
 
      var file, img; 
 
      if ((file = this.files[0])) { 
 
       img = new Image(); 
 
       img.onload = function() { 
 
        var size = parseFloat(self[0].files[0].size/1024); 
 
        var height = this.height; 
 
        var width = this.width; 
 
        console.log("Size is in KB " + size); 
 
        console.log("Height: " + height); 
 
        console.log("Width: " + width); 
 
        if (size > 100) { 
 
         self.val(''); 
 
         } 
 
       }; 
 
       img.src = _URL.createObjectURL(file); 
 
      } 
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="file" id="file" />

+0

偉大的作品,謝謝! – dataatallured