加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular文件上传进度百分比

发布时间:2020-12-17 07:55:03 所属栏目:安全 来源:网络整理
导读:在我在Angular 4中开发的应用程序中,用户可以将多部分文件上传到服务器.文件很大.我需要显示文件上传过程的当前进度及其对用户的百分比,我该怎么办? 提前致谢! 由于您使用的是Angular4,因此可以使用@ angular / common / http中的新HttpClient使用 Listeni
在我在Angular 4中开发的应用程序中,用户可以将多部分文件上传到服务器.文件很大.我需要显示文件上传过程的当前进度及其对用户的百分比,我该怎么办?

提前致谢!

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

从文档中添加代码,

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包装为此answer中提到的Observable

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读