在Angular中下载文件时无法获取进度和文件

编程入门 行业动态 更新时间:2024-10-24 12:24:01
本文介绍了在Angular中下载文件时无法获取进度和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个Angular应用程序,我只想下载一个文件.

I have an Angular application where I just want to download a file.

到目前为止,这是我的代码:

Up until now, this was my code:

this.fileNavigationService.downloadFile(element).subscribe(result => { this.generateDownload(result); });

我的服务

downloadFile(file: FileElement) { return this.http.get(this.apiUrl + '/downloadFile', { params: file.name, responseType: 'blob' }); }

现在,我想在下载文件时显示进度.在网上查找后,我发现了一些非常有用的东西.我的服务现在看起来像这样:

Now, I wanted to show the progression when I download a file. After looking up online, I came across something quite useful. My service now looks like this:

downloadFile(file: FileElement) { const req = new HttpRequest('GET', '/downloadFile?path=' + file.name, { reportProgress: true, }); return this.http.request(req).subscribe(event => { if (event.type === HttpEventType.DownloadProgress) { const percentDone = Math.round(100 * event.loaded / event.total); console.log(`File is ${percentDone}% downloaded.`); } else if (event instanceof HttpResponse) { console.log('File is completely downloaded!'); } }); }

我可以在控制台中清楚地看到进度,但是,现在有两个问题:

I can clearly see in my console the progress, however, I have now 2 problems:

  • 即使下载似乎已达到100%,我的代码也永远不会进入最后一个 if
  • 我的组件中的代码显然在订阅方法上被破坏了
  • My code never goes into the last if even though the download appears to reach 100%
  • The code in my component is obviously broken on the subscribe method

预订"类型上不存在预订"属性.

Property 'subscribe' does not exist on type 'Subscription'.

但是我似乎找不到找到使之可行的方法,因此我可以获取进度和结果文件.

But I can't seem to find a way to make this works so I can get the progression and my result file.

您有什么想法或例子可以帮助我吗?谢谢.

Do you have any idea or examples to help me on this? Thanks.

推荐答案

经过研究,终于有了此答案,我终于设法解决了我的问题.

现在这是我的服务代码:

This is now my service code:

downloadFile(file: FileElement) { return this.http.get( this.apiUrl + '/downloadFile', { params: file.name, responseType: 'blob', reportProgress: true, observe: 'events', headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } ); }

在我的组件中:

this.fileNavigationService.downloadFile(element).subscribe(result => { if (result.type === HttpEventType.DownloadProgress) { const percentDone = Math.round(100 * result.loaded / result.total); console.log(percentDone); } if (result.type === HttpEventType.Response) { this.generateDownload(result.body); } });

更多推荐

在Angular中下载文件时无法获取进度和文件

本文发布于:2023-11-26 07:08:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633126.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   进度   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!