从Angular 2中的FileReader获取数据 [英] Getting Data from FileReader in Angular 2

查看:441
本文介绍了从Angular 2中的FileReader获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 2 ts(2.2.1)中创建一个上传表单,允许上传例如一个CSV文件,但不是直接发送到http服务的文件,我希望首先在浏览器中验证该文件。

I am trying to create an upload form in Angular 2 ts (2.2.1), that allows the upload of e.g. a CSV file, but instead of the file being sent straight to a http service I want the file first to be validated in the browser.

到目前为止,我已经可以上传一个文件并使用以下代码在控制台中打印:

So far I can already upload a file and print it in the console with this code:


  1. 文件上传的Html输入

  1. Html input for file upload

<input type="file" (change)="changeListener($event)" #input />


  • 在我的角度组件中,我设置了eventListner和文件阅读器。

  • In my angular component I have set up the eventListner and the File reader.

    export class UploadComponent {
    
        public fileString;
    
        constructor() {
            this.fileString;
        }
    
        changeListener($event): void {
                this.readThis($event.target);
            }
    
        readThis(inputValue: any): void {
            var file: File = inputValue.files[0];
            var myReader: FileReader = new FileReader();
            var fileType = inputValue.parentElement.id;
            myReader.onloadend = function (e) {
                //myReader.result is a String of the uploaded file
                console.log(myReader.result);
    
                //fileString = myReader.result would not work, 
                //because it is not in the scope of the callback
            }
    
            myReader.readAsText(file);
        }
    }
    


  • 到目前为止,这段代码完全正常。

    This code works perfectly fine so far.

    但是我还没有找到一种方法来存储来自阅读器的数据,这种方式允许我用我的角度访问它组件。

    However I have not found a way to store the data from the reader in a way that allows me to access it with my angular component.

    myReader.onloadend()回调函数无权访问组件的变量。有没有办法注入这些变量?

    The myReader.onloadend() callback function does not have access to the component's variables. Is there some way to inject those variables?

    如何将读取的数据放入我的 fileString 变量中组件?

    How can I get the read data into the fileString variable in my component?

    推荐答案

    这样做:

    myReader.onloadend = (e) => {
       console.log(myReader.result);
       this.fileString = myReader.result;
    };
    

    所以你可以访问你的变量。

    So you can access your variables.

    有关更详细的说明: https://developer.mozilla。 org / de / docs / Web / JavaScript / Reference / Functions / Arrow_functions

    这篇关于从Angular 2中的FileReader获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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