4

I'm just learning how to use the filereader now, and I duplicated an example I found online to experiment with, but for some reason, the filereader always returns an empty string.

First, I have an HTML form for the user to select a file, which then calls the script:

<input type="file" id="filelist" onchange="selectfile()">

Here's the script:

function selectfile() {
        myFile = document.getElementById("filelist").files[0];
        reader = new FileReader();
        
        reader.readAsText(myFile);
    
        myResult = reader.result;
        
        alert(myFile.name);
        alert(myResult);
        alert(reader.error);
    }

I have tried this with a number of different text files I typed up in Notepad, and in every case the results are the same. I'm only ever submitting one file through the html form.

The 3 alerts are for testing.

It displays the file name correctly. It displays an empty string for the result. It displays NULL for the error so it's not getting an error.

I searched around to see if there was something obvious here already, but couldn't find anything that seemed to point me in the right direction.

Thoughts?

2
  • 1
    FileReader methods are asynchronous - you'll need to use FileReader events to access completed reads Commented Aug 10, 2020 at 23:11
  • Perhaps the first result for searching javascript using filereader will enlighten you - javascripture.com/FileReader Commented Aug 10, 2020 at 23:15

1 Answer 1

2

The FileReader object is not ready yet. You need to add an onload event listener to the reader and then make a call to the readAsText method. You can then access the file contents from inside the callback function.

MDN docs - https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result

function selectfile() {
    myFile = document.getElementById("filelist").files[0];
    reader = new FileReader();

    reader.onload = () => {
        myResult = reader.result;

        alert(myFile.name);
        alert(myResult);
        alert(reader.error);
    };


    reader.readAsText(myFile); // only accessible when the FileReader is loaded
}
<input type="file" id="filelist" onchange="selectfile()">

Sign up to request clarification or add additional context in comments.

Comments

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.