Shawn
Shawn

Reputation: 363

How to load file in TypeScript

I'm new at Typescript and have a syntax problem. I want to load a user selected file (not using JQuery) and print the results to the console for now. I was following some guides in JS but with no success. This is what I have so far.

index.html

<input type="file" id="file-input" >

index.ts

document.getElementById("file-input").addEventListener("change", e => {
  var reader = new FileReader();
  var self = this;
  reader.onload = file => {
      var contents: any = file.target;
      self.text = contents.result; 
  };
  console.log(self.text.toString());
}, false);  

This gives the following error in the console report:

Uncaught TypeError: Cannot read property 'toString' of undefined
    at HTMLInputElement.<anonymous>

I'm not quite sure how to get the text from the buffer or if I'm even setting it up correctly.

UPDATE: Current code with modifications:

document.getElementById("file-input").addEventListener("change", async (e) => {
  var file = (<HTMLInputElement>e.target).files[0];
  var reader = new FileReader();
  reader.onload = file => {
      var contents: any = file.target;
      this.text = contents.result; 
      console.log(this.text.toString());
  };
}, false);

Upvotes: 1

Views: 1477

Answers (1)

basarat
basarat

Reputation: 276125

Focus in on the code

  reader.onload = file => {
      var contents: any = file.target;
      self.text = contents.result; 
  };
  console.log(self.text.toString());

The order of execution you think it has:

  reader.onload = file => {
      var contents: any = file.target;
      self.text = contents.result; // FIRST 
  };
  console.log(self.text.toString()); // SECOND 

The order of execution in reality:

  reader.onload = file => {
      var contents: any = file.target;
      self.text = contents.result; // SECOND
  };
  console.log(self.text.toString()); // FIRST 

Hence you are getting the error as .text isn't assigned by the time self.text.toString runs.

FIX

One way:

  reader.onload = file => {
      var contents: any = file.target;
      self.text = contents.result; // FIRST
      console.log(self.text.toString()); // SECOND 🌹
  };

Upvotes: 1

Related Questions