2017-03-21 5 views
0

jQueryを使用して2MB未満のサイズの画像のみを使用して入力アップロード画像を検証したいとします。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); 
     } 
    }); 
}); 
+0

これはあなたを助けることを願っています。 http://stackoverflow.com/questions/1601455/how-to-check-file-input-size-with-jquery – Unknown

+0

[jQueryでファイルの入力サイズをチェックする方法は?](http://stackoverflow.com)/question/1601455/how-to-check-file-input-size-with-jquery) –

+0

これまでの回答から分かるように、 'Image' web APIは役に立ちません。ファイルサイズは画像専用ではなく、 'File' APIがレスキューになります。 –

答えて

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

})。

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; 
} 

スニペット

$(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); 
 
    } 
 
    }); 
 
});
<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">

関連する問題