typescript 上传和读取文件客户端,角度为 2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39297722/
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
Upload and read file client side, with angular 2
提问by Katu
I need log file(s) from user so I can read and analyze those. For example somekind of drop area, where user drops a file, then I can read it with javascript?
我需要来自用户的日志文件,以便我可以阅读和分析这些文件。例如某种放置区域,用户放置文件的地方,然后我可以用javascript读取它?
I use Angular2 rc5. I have node.js running backside, but I don't need the data there. I need it only at client side.
我使用 Angular2 rc5。我在后台运行 node.js,但我不需要那里的数据。我只在客户端需要它。
Is it possible to read and parse file content with just frontend tech, like angular2 and javascript? Or do I have to upload the file to server and analyze it there?
是否可以仅使用前端技术(例如 angular2 和 javascript)来读取和解析文件内容?还是我必须将文件上传到服务器并在那里进行分析?
回答by Katu
It is possible!
有可能的!
I ended up doing it like this. This reads all the files that are selected with file dialog. I don't need to send these to node.js. I can just manipulate these on client.
我最终这样做了。这将读取使用文件对话框选择的所有文件。我不需要将这些发送到 node.js。我可以在客户端上操作这些。
<input type='file' accept='text/plain' multiple (change)='openFile($event)'>
openFile(event) {
let input = event.target;
for (var index = 0; index < input.files.length; index++) {
let reader = new FileReader();
reader.onload = () => {
// this 'text' is the content of the file
var text = reader.result;
}
reader.readAsText(input.files[index]);
};
}
It is very basic example of how you can do it.
这是如何做到这一点的非常基本的例子。