How to check file input size with jQuery?

Viewed 365493

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?

9 Answers

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;

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

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

HTML code:

<input type="file" id="upload" class="filestyle" onchange="SizeCheck();"/>

JavaScript Function:

function SizeCheck() {
            var fileInput = document.getElementById('upload').files;
            var fsize = fileInput[0].size;
            var file = Math.round((fsize / 1024));
            if (file >= 10240) {     //10MB
               //Add Alert Here If 
                $('#upload_error').html("* File Size < 10MB");
            }
            else {
                $('#invoice_error').html("");
            }
        }
Related