Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Filereader always returns empty string?

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?

like image 575
Greg Steiner Avatar asked Sep 07 '25 04:09

Greg Steiner


1 Answers

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()">
like image 103
Cody Pace Avatar answered Sep 08 '25 17:09

Cody Pace