How to make FileReader work with Angular2?

后端 未结 5 1670
醉酒成梦
醉酒成梦 2020-12-06 01:32

How to make FileReader work with Angular2!!

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

I try to us

5条回答
  •  无人及你
    2020-12-06 01:55

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

    @View({
      template:`
        
    Select file:
    ` })

    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.

提交回复
热议问题