Javascript 如何使 FileReader 与 Angular2 一起工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30830268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make FileReader work with Angular2?
提问by butaixianran
How to make FileReader work with Angular2!!
如何使 FileReader 与Angular2 一起工作!!
When reading a file from client side with Angular2and Typescript,
使用Angular2和 Typescript从客户端读取文件时,
I try to use FileReader in this way:
我尝试以这种方式使用 FileReader:
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.
但它根本不起作用,永远不会调用这个“fileReader.onload”函数。
Really need a solution for reading files, please help. Thanks
真的需要一个读取文件的解决方案,请帮忙。谢谢
Check this from an online IDE:
从在线 IDE 中检查:
preview: https://angular2-butaixianran.c9.io/src/index.html
预览:https: //angular2-buttaixianran.c9.io/src/index.html
回答by haz111
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()方法绑定到(change)事件。我的类实现:
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 readThismethod. Read this have implemented it's own FileReader. You can also define FileReader in component instead in function.
侦听器正在将文件从事件传递到readThis方法。阅读这个已经实现了它自己的FileReader. 您还可以在组件中而不是在函数中定义 FileReader。
回答by user3124360
answer from @haz111 already works, but just in case you want to make file reader a reusable component , you could possibly use this or better: improve on this:
来自@haz111 的回答已经有效,但万一你想让文件阅读器成为一个可重用的组件,你可能会使用这个或更好的:改进这个:
inputfilereader.ts
输入文件阅读器.ts
import {Component, ElementRef, EventEmitter} from 'angular2/angular2';
@Component({
selector: 'filereader',
templateUrl: './commons/inputfilereader/filereader.html',
styleUrls: ['./commons/inputfilereader/filereader.css'],
providers: [ElementRef],
events : ['complete']
})
export class InputFileReader {
complete :EventEmitter = new EventEmitter();
constructor(public elementRef: ElementRef) {
}
resultSet:any; // dont need it
changeListener($event: any) {
var self = this;
var file:File = $event.target.files[0];
var myReader:FileReader = new FileReader();
myReader.readAsText(file);
var resultSet = [];
myReader.onloadend = function(e){
// you can perform an action with data read here
// as an example i am just splitting strings by spaces
var columns = myReader.result.split(/\r\n|\r|\n/g);
for (var i = 0; i < columns.length; i++) {
resultSet.push(columns[i].split(' '));
}
self.resultSet=resultSet; // probably dont need to do this atall
self.complete.next(self.resultSet); // pass along the data which would be used by the parent component
};
}
}
filereader.html
文件阅读器.html
<input type="file" (change)="changeListener($event)" />
Usage in other files
在其他文件中的使用
anotherfile lets say dfs.ts
另一个文件可以说 dfs.ts
import {Component, ElementRef} from 'angular2/angular2';
import {InputFileReader} from '../../commons/inputfilereader/inputfilereader';
@Component({
selector: 'dfs',
templateUrl: './components/dfs/dfs.html',
styleUrls: ['./components/dfs/dfs.css'],
providers: [ElementRef],
directives:[InputFileReader]
})
export class DfsCmp {
constructor(public eleRef :ElementRef) {}
callSomeFunc(data):void {
console.log("I am being called with ", data);
}
}
dfs.html
dfs.html
<filereader (complete)="callSomeFunc($event)"></filereader>
回答by afmeva
a little late to the party here. This can also be done creating the FileReader as service. This would help the unit tests and will decouple the FileReader from the component that is using it.
这里的聚会有点晚了。这也可以通过创建 FileReader 作为服务来完成。这将有助于单元测试并将 FileReader 与使用它的组件分离。
you can create the token like this:
您可以像这样创建令牌:
export const FileReaderService = new InjectionToken<FileReader>('FileReader', {
factory: () => new FileReader(),
});
And then you can use it as like this: (I believe it could be used as a regular service. I haven't tested it yet. But the way I am showing here works just fine)
然后你可以像这样使用它:(我相信它可以用作常规服务。我还没有测试过。但我在这里展示的方式很好用)
class MyService { // this could be a component too
constructor(@Inject(FileReaderService) private reader: FileReader) {}
readFile() {
const file = // the file you want to read
this.reader.onload = // whateever you need
this.reader.readAsDataURL(file)
}
}
回答by Reza
I would create a method like below
我会创建一个如下所示的方法
readFileContent(file: File): Promise<string | ArrayBuffer> {
return new Promise<string | ArrayBuffer>((resolve, reject) => {
const myReader: FileReader = new FileReader();
myReader.onloadend = (e) => {
resolve(myReader.result);
};
myReader.onerror = (e) => {
reject(e);
};
myReader.readAsText(file);
});
}
and call it like
并称之为
const content = await this.readFileContent(inputValue.files[0])
回答by Camilo Soto
Just add
只需添加
fr.readAsText(event.files[0]);
After the onLoad definition.
在 onLoad 定义之后。
Maybe this can help you, this is my upload handler function for the file upload library of primeng
也许这可以帮助你,这是我的primeng文件上传库的上传处理函数
archivoUploadHandler(event) {
let contenido;
let fr = new FileReader();
fr.onload = (e) => {
contenido = fr.result;
console.log(contenido);
};
fr.readAsText(event.files[0]);
}

