角度文件上传进度百分比 [英] Angular file upload progress percentage

查看:162
本文介绍了角度文件上传进度百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用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?

提前谢谢!

推荐答案

由于您使用的是Angular4,因此可以使用

Since you are using Angular4 , it can be achieved using Listening to progress events using the new HttpClient from @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一起使用,因此应使用本

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

这篇关于角度文件上传进度百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆