有角度的文件上传进度百分比(Angular file upload progress percentage)

编程入门 行业动态 更新时间:2024-10-18 22:34:07
有角度的文件上传进度百分比(Angular file upload progress percentage)

在我在Angular 4中开发的应用程序中,用户可以将多部分文件上传到服务器。 文件很大。 我需要显示文件上传过程的当前进度及其对用户的百分比,我该怎么做?

提前致谢!

In my application that i am developing in Angular 4, user can upload multipart files into server. Files are large. I need to show the current progress of file upload process with it's percentage to user, how can i do it?

Thanks in advance!

最满意答案

由于您使用的是Angular4,因此可以使用@angular/common/http.的新HttpClient Listening to progress事件@angular/common/http.

从文档添加代码,

const req = new HttpRequest('POST', '/upload/file', file, { reportProgress: true, });

接着,

http.request(req).subscribe(event => { // Via this API, you get access to the raw event stream. // Look for upload progress events. if (event.type === HttpEventType.UploadProgress) { // This is an upload progress event. Compute and show the % done: const percentDone = Math.round(100 * event.loaded / event.total); console.log(`File is ${percentDone}% uploaded.`); } else if (event instanceof HttpResponse) { console.log('File is completely uploaded!'); } });

编辑由于OP想与angular2一起使用它,应该使用原生JavaScript XHR作为Observable包装,如此answer

Since you are using Angular4 , it can be achieved using Listening to progress events using the new HttpClient from @angular/common/http.

Adding code from the docs,

const req = new HttpRequest('POST', '/upload/file', file, { reportProgress: true, });

and then,

http.request(req).subscribe(event => { // Via this API, you get access to the raw event stream. // Look for upload progress events. if (event.type === HttpEventType.UploadProgress) { // This is an upload progress event. Compute and show the % done: const percentDone = Math.round(100 * event.loaded / event.total); console.log(`File is ${percentDone}% uploaded.`); } else if (event instanceof HttpResponse) { console.log('File is completely uploaded!'); } });

EDIT Since OP wanted to use it with angular2, should use native JavaScript XHR wrapped as an Observable as mentioned in this answer

更多推荐

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

发布评论

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

>www.elefans.com

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