Tuesday, December 23, 2014

Javascript Client Side File Size Validation

When you attempt to upload a file that is larger than the web server will accept, it just stops processing. It might be OK, but you don't have a way to be notified. It would be nice to be able to do have something like the following code snippet.
$("#editDialog form").submit(function( event ) {
    return validateFileSize('profile_image', 1024*1024*2, 'Profile Image', event);
});
The solution is very simple with the HTML5 file reader functionality. We can add some JavaScript to run before we attempt to send the bad files. The following achieves the validation needed.
function validateFileSize(id, limit, label, event) {
    if (typeof FileReader !== "undefined" && document.getElementById(id).files.length > 0) {
        var size = document.getElementById(id).files[0].size;
        if (size > limit) {
            alert(label + ' is too large.  The file must be less than ' + formatSize(limit) + '.');
            event.preventDefault();
            return false;
        }
    }
    return true;
}
I am utilizing my JavaScript function from my previous post JavaScript Format File Size Truncate Decimals. This allows me to format the file size very nicely.
function formatSize(bytes, decimals) {
    if (!!!bytes) return 'n/a';
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'],
        i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))),
        decMult = Math.pow(10, decimals || 2);
    return (Math.round((bytes / Math.pow(1024, i)) * decMult)) / decMult + ' ' + sizes[i];
}

No comments: