首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用angular2 http API跟踪上载/下载进度

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

Stack Overflow用户
提问于 2017-02-14 16:19:10
回答 3查看 27K关注 0票数 30

因此,在angular2中有许多支持上载/下载进度的临时库,我不知道如何在进行上载/下载时使用本机angular2 http来显示进度。

我想使用本机http api的原因是因为我想利用:

  1. 本地http API周围的http拦截器(http api包装器),用于验证、缓存和丰富实际发送的http请求,如
  2. 角的http比任何特殊的api都要健壮得多

有关于如何使用角的http进行上载/下载的一篇好文章

但这篇文章提到,没有支持进步的原生方式。

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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-07-20 18:19:59

的角度为4.3.x,超过了版本,它可以使用来自@angular/common/http的新HttpClient实现。

阅读倾听进度事件部分。

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

代码语言:javascript
运行
复制
    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!');
      }
    });

而对于下载来说,可能也是一样的:

代码语言:javascript
运行
复制
    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,否则,无法测量请求。

票数 55
EN

Stack Overflow用户

发布于 2017-02-14 20:38:47

我建议使用包装为可观察的本机JavaScript XHR,很容易自己创建:

代码语言:javascript
运行
复制
upload(file: File): Observable<string | number> {

    let fd: FormData = new FormData();

    fd.append("file", file);

    let xhr = new XMLHttpRequest;

    return Observable.create(observer => {

        xhr.addEventListener("progress", (progress) => {

            let percentCompleted;

            // Checks if we can really track the progress
            if (progress.lengthComputable) {

                // progress.loaded is a number between 0 and 1, so we'll multiple it by 100
                percentCompleted = Math.round(progress.loaded / progress.total * 100);

                if (percentCompleted < 1) {
                    observer.next(0);
                } else {
                    // Emit the progress percentage
                    observer.next(percentCompleted);
                }
            }
        });

        xhr.addEventListener("load", (e) => {

            if (e.target['status'] !== 200) observer.error(e.target['responseText']);

            else observer.complete(e.target['responseText']);
        });

        xhr.addEventListener("error", (err) => {

            console.log('upload error', err);

            observer.error('Upload error');
        });

        xhr.addEventListener("abort", (abort) => {

            console.log('upload abort', abort);

            observer.error('Transfer aborted by the user');
        });

        xhr.open('POST', 'http://some-dummy-url.com/v1/media/files');

        // Add any headers if necessary
        xhr.setRequestHeader("Authorization", `Bearer rqrwrewrqe`);

        // Send off the file
        xhr.send(fd);

        // This function will get executed once the subscription
        // has been unsubscribed
        return () => xhr.abort()
    });
}

这就是人们如何使用它的方式:

代码语言:javascript
运行
复制
// file is an instance of File that you need to retrieve from input[type="file"] element
const uploadSubscription = this.upload(file).subscribe(progress => {
    if (typeof progress === Number) {
        console.log("upload progress:", progress);
    }
});

// To abort the upload
// we should check whether the subscription is still active
if (uploadSubscription) uploadSubscription.unsubscribe();
票数 3
EN

Stack Overflow用户

发布于 2021-04-01 11:23:09

现在这是可能的,请查看https://angular.io/guide/http#tracking-and-showing-request-progress

我可以在这里举一个例子,但是我认为从角度的文档中的官方例子会更好。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42231123

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档