如何使用 angular2 http API 跟踪 upload/download 进度

How to use angular2 http API for tracking upload/download progress

虽然在 angular2 中有许多支持 upload/download 进度的临时库,但我不知道如何使用本机 angular2 http api 来显示进度在做 upload/download.

之所以要使用原生httpapi是因为我想利用

  1. 围绕原生 http api 的 http 拦截器(http API 包装器)验证、缓存和丰富正在发送的实际 http 请求,例如 this & this
  2. 此外 angular 的 http api 比任何 adhoc APIs
  3. 都要强大得多

关于如何使用 angular 的 http api

upload/download 有 this nice article

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

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

如果不是,您是否知道 angular 存储库中的问题?

我建议使用原生的 JavaScript XHR 包装成一个 Observable,它很容易自己创建:

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()
    });
}

这就是使用它的方式:

// 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();

自 Angular 4.3.x 及更高版本 起,可以使用 [=12= 中的新 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', {
      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,否则无法测量请求。

现在可以了,查看 https://angular.io/guide/http#tracking-and-showing-request-progress

我可以在这里举个例子,但我认为 Angular 文档中的官方例子会更好