Get File Size from Input Control

A cross browser code snippet in JavaScript for getting file size from input element/control.


//return file size in bytes
function getFileSize( inputFile ) {
    var files = inputFile.files;
    if( !files ) {
        //for IE
        try {
            var fs = new ActiveXObject( 'Scripting.FileSystemObject' );
            var file = fs.getFile( inputFile.value );
            return file.size;
        } catch( ex ) {
            return -1;
    } else if( files.length > 0 ) {
        //for rest of the world
        return files[ 0 ].size;

Above function takes a reference to input file element and returns the file size in bytes. All browsers (except IE) support files collection which contain information (name, type, size) for each file selected using input control. You can find files collection using document.getElementById( ‘myInputFile’ ).files and files[ 0 ].size to get the size of selected file.

If files collection is not defined, it means it’s IE. You can use FileSystemObject to get file size. When creating ActiveXObject, an exception “Automation Server Can’t Create Object” can occur. That’s why I placed the IE part in try catch. This exception means that creating FileSystemObject is marked as not safe to instantiate. In such a case -1 is returned from this function. If no exception occurs automatically, IE will warn you with the following message.

IE FileSystemObject Warning

Or you may get this warning.

IE FileSystemObject Warning

Clicking Yes/Allow will return the size correctly. Otherwise same exception will occur.

Take a look at demo for clear understanding. Also check the DOMContentLoaded part in demo.

Note for IE Users: As I used addEventListener for attaching events in the demo, it will work in IE9+.


  1. Using Files from Web Applications
  2. FileSystemObject

comments powered by Disqus