JQuery 验证大小 < 2mb 的图像

Lee*_*Lee 2 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">
Run Code Online (Sandbox Code Playgroud)

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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

Ric*_*. M 5

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