In this article I will explain how to enforce file size limit by checking File size before upload using HTML5.
HTML5 allows developers to access the file contents and details using JavaScript and jQuery and hence in browsers that support HTML5 one can easily determine the size of the File.
 
Determining the size of the file using JavaScript and HTML5
The following HTML markup consists of an HTML FileUpload and a Button. When the button is clicked, a function named Upload is executed.
Inside this function, first a check is performed to verify whether the browser supports HTML5 File API. If the browser supports HTML5 File API then the size of the file is determined and the displayed.
<input type="file" id="fileUpload" />
<input type="button" value="Upload" onclick="Upload()" />
<script type="text/javascript">
    function Upload() {
        var fileUpload = document.getElementById("fileUpload");
        if (typeof (fileUpload.files) != "undefined") {
            var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
            alert(size + " KB.");
        } else {
            alert("This browser does not support HTML5.");
        }
    }
</script>
 
 
Determining the size of the file using jQuery and HTML5
The following HTML markup consists of an HTML FileUpload and a Button. When the button is clicked, a jQuery click event handler is executed.
Inside the click event handler, first a check is performed to verify whether the browser supports HTML5 File API. If the browser supports HTML5 File API then the size of the file is determined and the displayed.
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#upload").bind("click", function () {
            if (typeof ($("#fileUpload")[0].files) != "undefined") {
                var size = parseFloat($("#fileUpload")[0].files[0].size / 1024).toFixed(2);
                alert(size + " KB.");
            } else {
                alert("This browser does not support HTML5.");
            }
        });
    });
</script>
 
Screenshot
Check (Validate) File (Image) Size before upload using JavaScript and jQuery
 
 
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Demo
 
 
Downloads