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 .

1 Answer 1

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)}
    }
Sign up to request clarification or add additional context in comments.

5 Comments

@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?
@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
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
Ok. I get what you said. But I need file contents out of this handler. How I can achieve it?
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.