gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:45:11 26 4
gpt4 key购买 nike

我正在创建一个使用 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其中包含包含下载文件的数组缓冲区(作为主体成员)。

关于angular - 浏览器中的文件下载进度 : Angular 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51044553/

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