Detecting FileSize – jQuery

Hey everyone,

Just a quick post on how to detect a file’s size with jQuery. I’m currently using a version of this for basic client side validation:



    Upload image:
    

$(document).ready(function(){
    $('#image-file').bind('change', function() {
        
        var fileSize = this.files && this.files.length > 0 && this.files[0].size ? this.files[0].size / 1024 / 1024 : 0;
        
        if(fileSize > 0){
            $('body').append('
' + fileSize + ' MB
'); } else{ $('body').append('
' + fileSize + ' MB
'); } }); });
.file{
padding: 5px 7px;
border-radius: 3px;
background-color: green;
color: white;
margin: 5px;
}

.file.valid{
background-color: rgb(127, 197, 127);
}

.file.invalid{
background-color: rgb(197, 127, 127);
}

Here’s the link to the full fiddle: http://jsfiddle.net/nLLMF/

There’re also a whole heap of other options listed on this StackOverflow post if you’re chasing something a bit more robust: http://stackoverflow.com/a/13249924/522859

http://jsfiddle.net/nLLMF/embedded/


Posted

in

, ,

by

Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: