[ACCEPTED]-HTML5 File API: FileReader.readAsText() returns "undefined-fileapi

Accepted answer
Score: 16

That's not the way it works according to 3 the docs. You should call the readAsText() function, and 2 when it's completed the result is stored 1 in .result.

Score: 0

i found this example in this page of the docs 1 and it worked for me on the first try:

HTML:

<input type="file" onchange="previewFile()"><br>
<p class="content"></p>

JavaScript:

function previewFile() {
  const content = document.querySelector('.content');
  const [file] = document.querySelector('input[type=file]').files;
  const reader = new FileReader();

  reader.addEventListener("load", () => {
    // this will then display a text file
    content.innerText = reader.result;
  }, false);

  if (file) {
    reader.readAsText(file);
  }
}

More Related questions