FileReader onload不在控制器范围Angular 2中

时间:2016-05-09 19:44:15

标签: javascript typescript angular

我正在尝试以块的形式发送文件以保存在数据库中,并且我正在使用FileReader.readAsArrayBuffer()来触发onload事件。一旦我进入onload事件,我的问题就会发挥作用,'this'的范围只包含FileReader属性,而不包含我的类。甚至在onload事件之前定义的变量也是不可访问的。我以为我可以尝试将'this'的值作为参数传递给我,这样我就可以访问我的函数,服务和变量,但到目前为止我还没有取得任何成功。有没有人尝试过类似的东西,或者知道我是否达到了某种限制?

感谢您的帮助

这是我的组件类

export class UploadComponent {
title = 'Upload File';
fileData = null;
files = null;
fs;
@Input()
showUpload: boolean;

constructor(fileService: FileService) {
    this.fs = fileService;
}

uploadFile() {
    let temp = document.getElementById("fileToUpload");
    let fr = new FileReader();
    let file = temp.files[0];
    let fb = fr.readAsArrayBuffer(file);

    fr.onload = function(data) {
        this.fs.beginFileUpload(file.name, function(data) {
            let chunkSize = 200000;
            let startIndex = 0;
            let stopIndex = chunkSize;
            let file = data.target.result;
            let fileChunk = null;

            while (startIndex < file.length) {
                if (stopIndex < length) {
                    fileChunk = file.subArray(startIndex, stopIndex);
                    startIndex = stopIndex;
                    stopIndex += chunkSize;
                }
                else {
                    fileChunk = file.subArray(startIndex);
                    startIndex = stopIndex;
                }
                //fs.uploadChunk(fileChunk);
            }
        });

    }

}

}

我的组件模板

<input type="file" [(value)]="fileData" [(files)]="files" id="fileToUpload" />
<input type="button" (click)="uploadFile()" value="Upload File" />

1 个答案:

答案 0 :(得分:7)

使用() =>代替function()来保留this的范围

uploadFile() {
    let temp = document.getElementById("fileToUpload");
    let fr = new FileReader();
    let file = temp.files[0];
    let fb = fr.readAsArrayBuffer(file);

    fr.onload = (data) => {
        this.fs.beginFileUpload(file.name, (data) => {
            let chunkSize = 200000;
            let startIndex = 0;
            let stopIndex = chunkSize;
            let file = data.target.result;
            let fileChunk = null;

            while (startIndex < file.length) {
                if (stopIndex < length) {
                    fileChunk = file.subArray(startIndex, stopIndex);
                    startIndex = stopIndex;
                    stopIndex += chunkSize;
                }
                else {
                    fileChunk = file.subArray(startIndex);
                    startIndex = stopIndex;
                }
                //fs.uploadChunk(fileChunk);
            }
        });

    }
}

另见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions