JS - Show upload filesize

by Ben Clayton

HTML

There's a new feature from the W3C that's supported by some modern browsers, the File API. It can be used for this purpose, and it's easy to test whether it's supported and fall back (if necessary) to another mechanism if it isn't.

<br><br>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' >
<br><br>
<div id="message"></div>
</form>

JavaScript

$('#btnLoad').on('click',function showFileSize() {
    var input, file;
    // (Can't use `typeof FileReader === "function"` because apparently
    // it comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) {
        bodyAppend("p", "The file API isn't supported on this browser yet.");
        return;
    }

    input = document.getElementById('fileinput');
    if (!input) {
        bodyAppend("p", "Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
        bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
        bodyAppend("p", "Please select a file before clicking 'Load'");
    }
    else {
        file = input.files[0];
        bodyAppend("p", "File '" + file.name + "' is " + file.size + " bytes in size");
    }
});

function bodyAppend(tagName, innerHTML) {
    var elm;
    elm = document.getElementById('message');
    elm.innerHTML = innerHTML;
}