JavaScript file upload size validation

by Ben Clayton

HTML

<html>

  <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Show File Data</title>

    <script>
      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 " + formatFileSize(file.size,1));
        }
      }

      function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
      }

			function formatFileSize(bytes,decimalPoint) {
				 if(bytes == 0) return '0 Bytes';
				 var k = 1000,
						 dm = decimalPoint || 2,
						 sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
						 i = Math.floor(Math.log(bytes) / Math.log(k));
				 return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
			}

    </script>

  </head>

  <body>
    <form action='#' onsubmit="return false;">
      <input type='file' id='fileinput'>
      <input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
    </form>
  </body>

</html>

CSS

body {
  font-family: sans-serif;
}