在Angular 2中使用FileReader上载文件并读取数据 [英] Upload a File and Read Data with FileReader in Angular 2

查看:251
本文介绍了在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和File reader.

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

    因此您可以访问变量.

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

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

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