0

With the HTML File API we can get a file selected via an <input type="file"> element with var file = evt.target.files[0];.

How do we get the file content as a string (Something like var content = file.toString().

I currently have this code which gets triggered by the input element.onchange event:

input.onchange = function handleFileSelect(evt) {

var file = evt.target.files[0];
var reader = new FileReader();

console.log("RAW FILE: ", file);

var string = reader.readAsText(file);
console.log("FILE CONTENT: ", string);

}

When I select a file I try to log the contents this happens:

RAW FILE:  File
bundle.js:5293 FILE CONTENT:  undefined

Thoughts?

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

0

Turns out a file cannot just be read synchronously like this:

    var reader = new FileReader();
    content = reader.readAsText(file);

Before we can read the file we first have to attach to the onload event on the file reader.

    reader.onload = (e) => {
      let content = e.target.result;
      console.log("FILE CONTENT: ", content);
    }

The trigger the file read:

        reader.readAsText(file);

The content will now contain the file content.

Ole
  • 41,793
  • 59
  • 191
  • 359