浏览器中的文件下载进度:Angular 4



我正在创建一个使用 REST API 下载文件的应用程序。api 会在您点击文件时立即返回文件。所以我使用以下逻辑来获取文件:

downloadFile(file) {
this.service.downloadFile(file.id).subscribe((fileData) => {
const a = document.createElement('a');
document.body.appendChild(a);
const blob = new Blob([data], { type: data.type });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = file.name;
a.click();
window.URL.revokeObjectURL(url);
});

}

上面的代码完美运行。但是,当下载整个文件时,它会在浏览器中下载文件,即,您不会在浏览器中看到文件下载进度(我们通常在Chrome中下载文件时通常会看到(。您可以在控制台的"网络"选项卡中看到它正在下载文件,但仅在下载整个文件时显示。 任何人都可以告诉我如何强制它在浏览器中下载以显示进度吗?

你可以使用http.request方法

getFile():Observable<ArrayBuffer>{
return this.http.request('GET', 'https://raw.githubusercontent.com/bradleyflood/tool-sample-testing-images/master/jpg-beach-1900x1250-450kb.jpg',
{
observe: 'events',
reportProgress: true,
responseType: 'arraybuffer'
}).
map(event => this.getEventMessage(event))
.filter(f => f != null);

}
private getEventMessage(event: HttpEvent<any>) : ArrayBuffer {
switch (event.type) {
case HttpEventType.DownloadProgress:
// download in progress compute and show the % done:
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(event, percentDone);                 
return null;
case HttpEventType.Response:
//download finished return arraybody
return event.body;
default:
return null;
}
}

通过在请求中设置observe: 'events'选项,您可以查看所有请求事件,包括下载进度HttpEvent.DownloadProgress事件。 请求完成后,您将获得一个HttpEvent.Response其中包含包含下载文件的 ArrayBuffer(作为正文成员(。

最新更新