Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make FileReader work with Angular2?

How to make FileReader work with Angular2!!

When reading a file from client side with Angular2 and Typescript,

I try to use FileReader in this way:

var fileReader = new FileReader();
fileReader.onload = function(e) {
    console.log("run fileReader.onload");
   //  ......
}

But it doesn't work at all, this 'fileReader.onload' function will never be called.

Really need a solution for reading files, please help. Thanks

Check this from an online IDE:

preview: https://angular2-butaixianran.c9.io/src/index.html

editor: https://ide.c9.io/butaixianran/angular2

like image 335
butaixianran Avatar asked Jun 14 '15 14:06

butaixianran


1 Answers

First you have to specify the target of the change event on input form in template:

@View({
  template:`
    <div>
      Select file:
      <input type="file" (change)="changeListener($event)">
    </div>
  `
})

As you can see I binded a changeListener() method to (change) event. My implementation of class:

  changeListener($event) : void {
    this.readThis($event.target);
  }

  readThis(inputValue: any) : void {
    var file:File = inputValue.files[0]; 
    var myReader:FileReader = new FileReader();

    myReader.onloadend = function(e){
      // you can perform an action with readed data here
      console.log(myReader.result);
    }

    myReader.readAsText(file);
  }

Listener is passing file from event to readThis method. Read this have implemented it's own FileReader. You can also define FileReader in component instead in function.

like image 148
haz111 Avatar answered Nov 15 '22 19:11

haz111