gpt4 book ai didi

javascript - FileReader onload 不在 Controller 范围内 Angular 2

转载 作者:太空狗 更新时间:2023-10-29 18:09:09 24 4
gpt4 key购买 nike

我正在尝试以 block 的形式发送文件以保存在数据库中,并且我正在使用 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" />

最佳答案

使用 () => 而不是 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

关于javascript - FileReader onload 不在 Controller 范围内 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com