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

标签 http angular interceptor angular2-http

因此在angular2中有很多支持上传/下载进度的ad hoc库,我不知道如何在上传/下载时使用原生angular2 http api来显示进度。

我之所以要使用原生的http api是因为我想利用:

  1. 围绕原生 http api 的 http 拦截器(http API 包装器)验证、缓存和丰富正在发送的实际 http 请求,例如 this & this
  2. Angular 的 http api 比任何 ad hoc API 都要健壮得多

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

但是文章提到没有原生的方式来支持进度。

有人试过使用 http api 来显示进度吗?

如果不是,您是否知道 Angular repo 中的问题?

最佳答案

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

阅读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', {
      reportProgress: true,
    });

    http.request(req).subscribe(event => {
      // Via this API, 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,否则无法测量请求。

关于http - 如何使用 angular2 http API 跟踪上传/下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53947625/

相关文章:

angular - 为什么添加 HTTP 拦截器会导致 CORS 错误?

apache - 为什么 <myWebsite.com> :8080 works while <mywebsite. com> 不适用于在 Ec2 上运行的 tomcat 服务器?

javascript - 为什么组件在没有 `changeDetetectorRef.markForCheck` 的情况下检测不到内部状态变化?

Spring Boot 和 JWT - JSESSIONID 允许 REST 请求而不需要 JWT?

在在线正则表达式测试人员中工作时,正则表达式无法在 Angular Validators.pattern() 中工作

javascript - 无法完成与服务器的协商 - Angular + SignalR

java - 拦截器未调用且不可见(在日志中,在部署期间什么也看不到)

angularjs - 在 Angular 接口(interface)中重用方法

json - 使用 R 发布 JSON

asp.net - 如何在 IIS 6 上启用 HTTP PUT?