11

Consider the following code

function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var myFile = evt.target.files[0];
    var reader = new FileReader();
    reader.readAsText(myFile);
    var myString = reader.toString();
    alert(myString); // print  - "[object FileReader]"   
}

I try to get all the file content into String , for example if the file content is

helloWorld1
helloWorld2

I will get alert of that's content .

URL87
  • 10,667
  • 35
  • 107
  • 174

1 Answers1

13

That's not how you get the result of a FileReader. Modify your code to this:

function readSingleFile(evt) {
        //Retrieve the first (and only!) File from the FileList object
        var myFile = evt.target.files[0];
        var reader = new FileReader();
        reader.readAsText(myFile);
        reader.onload=function(){alert(reader.result)}
    }
markasoftware
  • 12,292
  • 8
  • 41
  • 69
  • @Markasoftware Hello. I am trying to do this. I did: `var bob; reader.onload=function(){bob = reader.result;} console.log(bob)'`.Console.log shows, that bob is undefined. Why? – Sharikov Vladislav Apr 12 '14 at 14:28
  • @SharikovVladislav This is because javascript is asynchronous. Let me go over how that code works. First, you do `var bob;`. That initializes an undefined variable named `bob`. Then, you do `reader.onload=function(){bob=reader.result}`, which sets an event listener. However, it simply sets the event listener. It does not wait for the event to occur, it simply sets a handler. So, the interpreter continues. It doesn't wait for reading to be done. So, when you do `console.log(bob)`, it logs undefined because the reader isn't done yet, because all you did was add a handler that will be called – markasoftware Apr 12 '14 at 18:50
  • once it finishes. To make it work properly, you need to put `console.log(bob)` inside of the `reader.onload` function, so that it isn't called until the reader is done reading. Sorry if that doesn't make sense, please ask any questions if you do not understand – markasoftware Apr 12 '14 at 18:51
  • Ok. I get what you said. But I need file contents out of this handler. How I can achieve it? – Sharikov Vladislav Apr 12 '14 at 19:54
  • you just have to put all of the code that needs access to the file contents inside of the handler (inside of the reader.onload handler) – markasoftware Apr 12 '14 at 22:59