从Angular 2中的FileReader获取数据

kac*_*ase 5 javascript filereader typescript angular

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

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

  1. 用于文件上传的Html输入

    <input type="file" (change)="changeListener($event)" #input />
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在我的角度组件中,我设置了eventListner和File阅读器.

    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);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

到目前为止,此代码完美无缺.

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

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

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

mxi*_*xii 18

像这样做:

myReader.onloadend = (e) => {
   console.log(myReader.result);
   this.fileString = myReader.result;
};
Run Code Online (Sandbox Code Playgroud)

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

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