How to check file input size with jQuery?

前端 未结 8 2326
渐次进展
渐次进展 2020-11-22 09:21

I have a form with file upload capabilities and I would like to be able to have some nice client side error reporting if the file the user is trying to upload is too big, is

相关标签:
8条回答
  • 2020-11-22 09:50
    <form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="file">
    </form>
    <button onclick="checkSize();"></button>
    <script>
        function checkSize(){
            var size = $('#uploadForm')["0"].firstChild.files["0"].size;
            console.log(size);
        }
    </script>
    

    I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.

    NOTES:

    var size = $('#uploadForm')["0"]["0"].files["0"].size;
    

    This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.

    0 讨论(0)
  • 2020-11-22 09:54

    I am posting my solution too, used for an ASP.NET FileUpload control. Perhaps someone will find it useful.

        $(function () {        
        $('<%= fileUploadCV.ClientID %>').change(function () {
    
            //because this is single file upload I use only first index
            var f = this.files[0]
    
            //here I CHECK if the FILE SIZE is bigger than 8 MB (numbers below are in bytes)
            if (f.size > 8388608 || f.fileSize > 8388608)
            {
               //show an alert to the user
               alert("Allowed file size exceeded. (Max. 8 MB)")
    
               //reset file upload control
               this.value = null;
            }
        })
    });
    
    0 讨论(0)
提交回复
热议问题