How to restrict image upload size to less than 2mb?

前端 未结 1 714
悲哀的现实
悲哀的现实 2021-01-21 20:50

I have an html select option for uploading images.

相关标签:
1条回答
  • 2021-01-21 21:24

    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 讨论(0)
提交回复
热议问题