如何使FileReader与Angular2一起使用? [英] How to make FileReader work with Angular2?

查看:99
本文介绍了如何使FileReader与Angular2一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使FileReader与 Angular2 一起使用!!

How to make FileReader work with Angular2!!

使用 Angular2 从客户端读取文件时和打字稿,

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

我尝试以这种方式使用FileReader:

I try to use FileReader in this way:

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

但它没有'总的来说,这个'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

从在线IDE中查看:

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

编辑:
https:// ide。 c9.io/butaixianran/angular2

推荐答案

首先,您必须在输入表单上指定更改事件的目标在模板中:

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>
  `
})

如你所见,我绑定了一个 changeListener()方法(更改)事件。我的类实现:

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);
  }

监听器将文件从事件传递到 readThis 方法。阅读本文已经实现了它自己的 FileReader 。您也可以在函数中定义组件中的FileReader。

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.

这篇关于如何使FileReader与Angular2一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆