在 Angular 2 中使用 FileReader 上传文件和读取数据

Upload a File and Read Data with FileReader in Angular 2

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

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

  1. Html 文件上传输入

    <input type="file" (change)="changeListener($event)" #input />
    
  2. 在我的 angular 组件中,我设置了 eventListner 和文件 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);
        }
    }
    

这段代码到目前为止工作得很好。

但是我还没有找到一种方法来存储来自 reader 的数据,并允许我使用我的 angular 组件访问它。

myReader.onloadend() 回调函数无法访问组件的变量。有什么方法可以注入这些变量吗?

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

这样做:

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

因此您可以访问您的变量。

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

mxii 的答案隐式转换为字符串,这对我不起作用,可能在 angular 的较新版本中不再允许。

对我有用的是;

JSON.parse(fileReader.result as string)

it work, try like this...

this.uploader.uploadAll = () => {
        console.log(this.uploader.queue.length)
        let fileCount: number = this.uploader.queue.length;
        if (fileCount > 0) {
            this.uploader.queue.forEach((val, i) => {
                var reader = new FileReader();
                reader.onloadend = (e) => {
                    var result = reader.result;
                    console.log(i + '/' + result)
                    this.file64.push(result)
                };
                reader.readAsDataURL(val._file);
            }
            );
        }
    }