如何在Angular 5中访问文件上载的HttpEvent进度?

时间:2018-05-01 06:02:53

标签: angular

我已经完成了angular.io文档以及其他SO的答案,但是我仍然无法解决如何从Angular 5到NodeJS访问POST调用的文件上传进度并显示给用户。 / p>

这就是我在做什么。

//组件代码:body是包含文件和其他一些字段的表单数据。

  this.fileService.uploadtool5(body, this.token).subscribe(res =>{

        if(res.success){
          //do something server has received post data
        }
      },(err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
              // A client-side or network error occurred. Handle it accordingly.
              //console.log('An error occurred:', err.error.message);
              //console.log('Status', err.status);
             // this.signupfailreasonstatus = err.status;
            } else {
              // The backend returned an unsuccessful response code.
              // The response body may contain clues as to what went wrong,
              //console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
              //console.log('Status', err.status);
            }
      });

//我有一个响应对象的拦截器,看起来像这样。

export interface Tool9Response {
  success: boolean;
  message: string;
} 

// fileService code

uploadtool5( payload, token ) : Observable<Tool9Response>{
       const httpOptions = {
         headers: new HttpHeaders({
           'Authorization': token
         })
       };
       return this.http.post<Tool9Response>(this._baseURL + 'appsecuritydesign', payload, httpOptions);

   }

我上传的大部分文件都是100多MB进行处理,因此上传需要时间,我想显示上传进度。如何在不更改我当前将数据发布到服务器的方式的情况下访问文件上载的HttpEvent进度?

1 个答案:

答案 0 :(得分:3)

在您的fileService代码中:

uploadtool5( payload, token ) : Observable<any> { // Assuming `payload` is FormData 

    const headers = new HttpHeaders({
       'Authorization': token
     })


   const req = new HttpRequest(
        'POST',      
         this._baseURL + 'appsecuritydesign', 
         payload, 
         { 
            headers:headers,
            reportProgress: true //This is required for track upload process
         }
   );

   return this.http.request(req);
 }

// component

this.fileService.uploadtool5(body, this.token).subscribe((event: HttpEvent<any>) => {

   if (event.type == HttpEventType.UploadProgress)
   {
     console.log("Loading: "+ event.loaded / (event.total || event.loaded) * 100 + '%');
   }
   if (event.type == HttpEventType.Response) {
     console.log("response:", event);
    /*success and message fields from the response can be accessed 
      here like this*/
     console.log("response:", event);
     console.log("body:", event.body);
     console.log("success:", event.body.success);
     console.log("message:", event.body.message);
   }


  });