2015-10-05 42 views
0

我试图上传大于900像素的图像。所以我确实上传时进行验证。当我们点击这个另一个文件按钮时,我会有加号。如何验证每次上传的图像大小

只有我得到的第一个输入框值。我无法获得其他文件。

<input type="file" id="upload_profile" class="upload_profile" name="upload_profile[]" /> 

脚本:

var _URL = window.URL || window.webkitURL; 
$(".upload_profile").change(function(e) { 
var file, img; 
if ((file = this.files[0])) { 
    img = new Image(); 
    img.onload = function() { 
     alert(this.width + " " + this.height); 
    }; 
    img.onerror = function() { 
     alert("not a valid file: " + file.type); 
    }; 
    img.src = _URL.createObjectURL(file); 
} 
}); 
+1

使用'$(文件)。在( '变', '.upload_profile',函数(E){...});' – Phylogenesis

+0

在你的代码的变量i没有定义(var file,img,i = 0;),如果我声明它,那么你的给定的代码工作正常。请使用提琴手了解更多http://fiddle.jshell.net/nzyu0q0q/ –

+0

@Phylogenesis:它的工作..谢谢 – ammni

回答

0

当连接事件等元素是不存在的DOM,你需要使用event delegation。事件委托允许我们将一个事件监听器附加到一个父元素,该元素将针对与选择器匹配的所有后代触发,无论这些后代是现在存在还是将来添加。

var _URL = window.URL || window.webkitURL; 
 
$(document).on('change', '.upload_profile', function() { 
 
if (this.value) { 
 
    var file = this.files[0]; 
 
    var img = new Image(); 
 
    img.onload = function() { 
 
     alert(this.width + " " + this.height); 
 
    }; 
 
    img.onerror = function() { 
 
     alert("not a valid file: " + file.type); 
 
    }; 
 
    img.src = _URL.createObjectURL(file); 
 
} 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="file" class="upload_profile" name="upload_profile[]" /><br><br> 
 
<input type="file" class="upload_profile" name="upload_profile[]" /><br><br> 
 
<input type="file" class="upload_profile" name="upload_profile[]" /><br><br>