Read a local file into a Javascript string

I needed to grab a local file and pull it into a Javascript string, I wanted to do this without any serverside support. I hack together the following short example, the same method can be used to pull in raw files for client-side processing:

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    for (var i = 0, f; f = files[i]; i++) {

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          var s = String.fromCharCode.apply(null, new Uint8Array(e.target.result));
          document.write(s);
        };
      })(f);

      // Read in the file as an ArrayBuffer
      reader.readAsArrayBuffer(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

Comments are closed.