在Angular 6中的for循环中一次上载一次文件
我正在尝试以Angular方式上载所有选定的文件。我创建了一个服务,它将文件作为表单数据传递给某个api在Angular 6中的for循环中一次上载一次文件,angular,file-upload,synchronization,Angular,File Upload,Synchronization,我正在尝试以Angular方式上载所有选定的文件。我创建了一个服务,它将文件作为表单数据传递给某个api onFileSelected(event: EventEmitter<File[]>) { for (let i = 0; i < this.uploader.queue.length; i++) { this.uploadedPercentage = 0; let fileItem = this.uploader.queue[i]._fi
onFileSelected(event: EventEmitter<File[]>) {
for (let i = 0; i < this.uploader.queue.length; i++) {
this.uploadedPercentage = 0;
let fileItem = this.uploader.queue[i]._file;
let f: FileDetail = { file: null, status: "", comment: "", uploadDate: new Date };
f.file = fileItem;
f.status = "init";
if (fileItem.size / 1024 / 1024 / 1024 <= 1) {
this.uploadFile(f, i);
}
else {
f.status = "error";
f.comment = "Maximum 1GB is allowed";
this.uploadedFiles.push(f);
}
}
}
uploadFile(file: FileDetail, index: number) {
let data = new FormData();
data.append('file', file.file);
data.append('filename', file.file.name);
var httpSubscriber : Subscription = this.service.uploadFileData(data).subscribe((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Sent:
break;
case HttpEventType.Response:
file.status = "Uploaded";
return true;
break;
case 1: {
if (Math.round(this.uploadedPercentage) !== Math.round(event['loaded'] / event['total'] * 100)) {
this.uploadedPercentage = event['loaded'] / event['total'] * 100;
}
file.status = "Uploading";
break;
}
}
});
}
问题:
我想上传文件一个接一个,并显示每个文件的进度。若你们在我的例子中看到,我采用for循环来上传所有文件,并调用了这个.uploadFile方法,该方法实际上将文件转换为多部分和调用服务。但由于它是异步方法,所以它显然不等待响应,而是一起开始上传文件。我想一个接一个地上传这个文件,并显示每个项目的进度。您可以使用async/await来等待Observable完成
首先,使uploadFile方法异步。然后等待uploadFileData操作完成。请注意,uploadFileData observable已转换为Promise
我在这里创建的一个小stackblitz项目:让我试试这个。你可以在更新的答案中找到stackblitz链接。
onFileSelected(event: EventEmitter<File[]>) {
for (let i = 0; i < this.uploader.queue.length; i++) {
...
if (fileItem.size / 1024 / 1024 / 1024 <= 1) {
this.uploadFile(f, i);
}
...
}
}
async uploadFile(file: FileDetail, index: number) {
...
await this.service.uploadFileData(data).toPromise().then((event: HttpEvent<any>) => {
switch (event.type) {
...
}
});
}