如何在Angular 5中跟踪文件上传进度并获取上传文件的URL

时间:2018-07-18 06:44:12

标签: angular httpclient

我正在研究Angle 5应用程序。其中,我需要上传图像并跟踪上传进度。我还需要获取文件上传api的响应。这是我的代码:

leftView

检查响应功能:

upload(){

      const fd = new FormData();
      fd.append('file', this.selectedFile, this.selectedFile.name);

      this.uploadImageApi(fd).subscribe(res => {this.apiResponse = res},
                                                      err => console.log(err),
                                                      ()  => this.checkUploadApiResponse(this.apiResponse, window)
                                                     );
     }

Api功能:

checkUploadApiResponse(response: any, window: Window)
{
    console.log(response);
}

2 个答案:

答案 0 :(得分:1)

您可以使用Progress事件检查上传状态!

import {
      HttpEventType,
      HttpClient,
      HttpRequest
    } from '@angular/common/http';

http.request(new HttpRequest(
  'POST',
  URL,
  body, 
  {
    reportProgress: true
  })).subscribe(event => {

  if (event.type === HttpEventType.DownloadProgress) {
     {
     }
  }

  if (event.type === HttpEventType.UploadProgress) {
     {
      }
  }

  if (event.type === HttpEventType.Response) {
    console.log(event.body);
  }

})

答案 1 :(得分:1)

您可以按照official documentation

中的收听进度事件来完成此操作

您必须使用dp编写服务函数,该函数将返回Observable<HttpEvent<any>>

public uploadFile(file: File): Observable<HttpEvent<any>> {
    const formData: FormData = new FormData();
    formData.append('uploadingFile', file, file.name);
    const req = new HttpRequest('POST', 'url', formData, {
      reportProgress: true
    });
    return this.http.request(req);
  }

并将服务注入到用于选择和上传文件的组件中。

public uploadFile(): void {
    if (this.file) {
      this.uploadSubscription = this.uploadServiceService
        .uploadFile(this.file)
        .pipe(map((data) => {
            this.getEventMessage(data, this.file);
          }),
          last())
        .subscribe(() => {

        }, () => {
          // on error
          this.percentage = 0;
        });
    }
  }

private getEventMessage(event: HttpEvent<any>) {
    switch (event.type) {
      case HttpEventType.Sent:
        this.percentage = 0;  // upload percentage
        break;

      case HttpEventType.UploadProgress:
        const percentDone = Math.round(100 * event.loaded / event.total);
        this.percentage = percentDone;
        break;

      case HttpEventType.Response:
        this.percentage = 100; // file is uploaded
        if (check the event status in here) {   // event.body 
          // show notifications/toast in here
          return;
        }
    }
  }

您可以使用percentage来显示进度条的百分比。使用event.body,您可以获得后端响应。

您可以编写这样的文件上传取消功能。

public cancelFileUpload(): void {
    if (this.uploadSubscription) {
      this.uploadSubscription.unsubscribe();
    }
  }