How to check file input size with jQuery?

JavascriptJqueryFile Upload

Javascript Problem Overview


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 there a way to check against file size with jQuery, either purely on the client or somehow posting the file back to the server to check?

Javascript Solutions


Solution 1 - Javascript

You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.

For the HTML below

<input type="file" id="myFile" />

try the following:

//binds to onchange event of your input field
$('#myFile').bind('change', function() {

  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);

});

As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/


Old browsers support

Be aware that old browsers will return a null value for the previous this.files call, so accessing this.files[0] will raise an exception and you should check for File API support before using it

Solution 2 - Javascript

If you want to use jQuery's validate you can by creating this method:

$.validator.addMethod('filesize', function(value, element, param) {
	// param = size (en bytes) 
	// element = element to validate (<input>)
	// value = value of the element (file name)
	return this.optional(element) || (element.files[0].size <= param) 
});

You would use it:

$('#formid').validate({
	rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

Solution 3 - Javascript

This code:

$("#yourFileInput")[0].files[0].size;

Returns the file size for an form input.

On FF 3.6 and later this code should be:

$("#yourFileInput")[0].files[0].fileSize;

Solution 4 - Javascript

Use below to check file's size and clear if it's greater,

    $("input[type='file']").on("change", function () {
     if(this.files[0].size > 2000000) {
       alert("Please upload file less than 2MB. Thanks!!");
       $(this).val('');
     }
    });

Solution 5 - Javascript

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

Solution 6 - Javascript

<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.

Solution 7 - Javascript

Plese try this:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

Solution 8 - Javascript

You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.

If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJimmyView Question on Stackoverflow
Solution 1 - JavascriptFelipe SabinoView Answer on Stackoverflow
Solution 2 - JavascriptNaoise GoldenView Answer on Stackoverflow
Solution 3 - Javascriptjeferod83View Answer on Stackoverflow
Solution 4 - JavascriptUmesh PatilView Answer on Stackoverflow
Solution 5 - JavascriptBesnik KastratiView Answer on Stackoverflow
Solution 6 - JavascriptDillon BurnettView Answer on Stackoverflow
Solution 7 - JavascriptBablu AhmedView Answer on Stackoverflow
Solution 8 - JavascriptKelseyView Answer on Stackoverflow