1

I can't figure out why neither readSuccess() or readFailure() are getting called in the following:

function readMyFile(){
    var reader = new FileReader();

    reader.onload = readSuccess;
    reader.onerror = readFailure;
    reader.readAsText("test.txt");

    function readSuccess(evt){
      alert(evt.target.result);
    }

    function readFailure(evt) {
      alert("Did not read file!");
    }
}

When I step though the code in the Chrome javascript debugger, it steps past the reader.readAsText("test.text"); command, but then exits the whole function, never calling readSuccess() or readFailure()

Chris Gregg
  • 2,376
  • 16
  • 30

1 Answers1

1

You can't specify a file with a string in reader.readAsText(), it needs to be a reference to a Blob: see the documentation.

You should be getting the Blob from a file-type input field, check out these awesome examples.

nwellcome
  • 2,279
  • 15
  • 23
  • Ah, okay, thanks. What if I want to specify a text file myself (this is for an internal file that I'll be reading only once). – Chris Gregg Aug 09 '11 at 17:46
  • Grabbing a `File` from the `FileList` of an input element is currently the only way to get at local files from a browser with javascript - but thank your stars for that, prior to HTML5 there was no way at all: http://stackoverflow.com/questions/371875/local-file-access-with-javascript – nwellcome Aug 09 '11 at 17:59