【问题标题】:File download progress in the browser: Angular 4浏览器中的文件下载进度:Angular 4
【发布时间】:2018-12-05 06:33:48
【问题描述】:

我正在创建一个使用 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 中下载文件时通常会看到)。您可以在控制台的“网络”选项卡中看到它正在下载文件,但仅在下载整个文件时才会显示。 谁能告诉我如何强制它在浏览器中下载以显示进度?

【问题讨论】:

    标签: angular


    【解决方案1】:

    你可以使用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 但你使用 jquery ;(
    猜你喜欢
    • 2014-11-18
    • 2015-10-27
    • 2019-08-26
    • 2017-02-15
    • 2014-10-27
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多