最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to restrict image upload size to less than 2mb? - Stack Overflow

programmeradmin5浏览0评论

I have an html select option for uploading images.

<div class="row smallMargin">
<div class="col-sm-6">
  Attach Image
</div>
<div class="col-sm-6">
  <input type="file" ng-model="image" accept="image/*">
</div>
</div>

How can I restrict the user from uploading images which are larger than 2MB?

I have an html select option for uploading images.

<div class="row smallMargin">
<div class="col-sm-6">
  Attach Image
</div>
<div class="col-sm-6">
  <input type="file" ng-model="image" accept="image/*">
</div>
</div>

How can I restrict the user from uploading images which are larger than 2MB?

Share Improve this question edited Sep 16, 2015 at 5:50 Craig 2,3763 gold badges24 silver badges39 bronze badges asked Sep 16, 2015 at 5:33 varunaervarunaer 731 gold badge2 silver badges11 bronze badges 2
  • Show me code of controller – Hardik Gondalia Commented Sep 16, 2015 at 5:37
  • 1 github./danialfarid/ng-file-upload check over this – Hardik Gondalia Commented Sep 16, 2015 at 5:39
Add a ment  | 

1 Answer 1

Reset to default 6

This example should give you an idea of how to do it:

HTML

<form  class="upload-form">
    <input class="upload-file" data-max-size="2048" type="file" >
    <input type=submit>
</form>

JS

$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more than ' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct - '+fileSize+' bytes');
            }
        }else{
            alert('Please select the file to upload');
            return false;
        }

    });
});
发布评论

评论列表(0)

  1. 暂无评论