我想使用 jQuery 验证我的输入上传图像,只允许大小小于 2mb 的图像。我四处寻找,但大多数指南都是关于验证尺寸(图像的宽度和高度)的,这是我的代码:
html:
<input type="file" name="logo" id="logo" accept="image/*">
<p class="error_line" style="display: none">Image Only</p>
<input class="btn btn-primary submit-btn" style="margin:10px 0; width: auto" type="submit" value="Create">
Javascript:
$(document).ready(function () {
var _URL = window.URL || window.webkitURL;
$("#logo").change(function(e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
$('.submit-btn').prop('disabled', false);
$(".error_line").fadeOut();
};
img.onerror = function() {
$('.submit-btn').prop('disabled', true);
$(".error_line").fadeIn();
};
img.src = _URL.createObjectURL(file);
}
});
});
最佳答案
$(document).ready(function() {
$('#logo').bind('change', function() {
var a=(this.files[0].size);
alert(a);
if(a > 2000000) {
alert('large');
};
});
});
关于JQuery 验证大小 < 2mb 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42922609/