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

如何使用angular2 http API跟踪上传/下载进度

发布时间:2020-12-17 07:55:41 所属栏目:安全 来源:网络整理
导读:有许多adhoc库支持angular2的上传/下载进度,我不知道如何使用native angular2 http api在上传/下载时显示进度. 我想使用原生http api的原因是因为我想利用它 本地http api周围的http拦截器(http API包装器),验证,缓存和放大器丰富发送的实际http请求,例如thi
有许多adhoc库支持angular2的上传/下载进度,我不知道如何使用native angular2 http api在上传/下载时显示进度.

我想使用原生http api的原因是因为我想利用它

>本地http api周围的http拦截器(http API包装器),验证,缓存和放大器丰富发送的实际http请求,例如this& this
>除了angular之外,http api比任何adhoc API都强大得多

关于如何使用angular的http api进行上传/下载有this nice article

但该文章提到,没有本土方式来支持进步.

有没有人尝试使用http api来显示进度?

如果没有,你知道角度回购中的问题吗?

从Angular 4.3.x及更高版本开始,可以使用@ angular / common / http中的新 HttpClient实现.

阅读Listening to progress events部分.

简单的上传示例(从上面提到的部分复制):

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!');
  }
});

而对于下载,它可能是几乎相同的东西:

const req = new HttpRequest('GET','/download/file',you get access to the raw event stream.
  // Look for download progress events.
  if (event.type === HttpEventType.DownloadProgress) {
    // This is an download progress event. Compute and show the % done:
    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!');
  }
});

请记住,如果您正在监控下载,则必须设置Content-Length,否则无法测量请求.

(编辑:李大同)

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

    推荐文章
      热点阅读