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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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.