我正在尝试以块的形式发送文件以保存在数据库中,并且我正在使用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()来保留这个范围
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。