JQuery验证大小<的图像2MB

时间:2017-03-21 09:10:40

标签: jquery

我想验证我的输入上传图像,只使用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);
        }
    });
});

2 个答案:

答案 0 :(得分:2)

$(document).ready(function() {       
$('#logo').bind('change', function() {
    var a=(this.files[0].size);
    alert(a);
    if(a > 2000000) {
        alert('large');
    };
});

});

答案 1 :(得分:1)

试试这个,

 if(Math.round(file.size/(1024*1024)) > 2){ // make it in MB so divide by 1024*1024
    alert('Please select image size less than 2 MB');
    return false;
 }

片段

&#13;
&#13;
$(document).ready(function() {
  var _URL = window.URL || window.webkitURL;
  $("#logo").change(function(e) {
    var file = this.files[0], img;
    if (Math.round(file.size / (1024 * 1024)) > 2) { // make it in MB so divide by 1024*1024
       alert('Please select image size less than 2 MB');
       return false;
    }
    if (file) {
      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);
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<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">
&#13;
&#13;
&#13;

相关问题