【问题标题】:How do I access the HttpEvent progress for file upload in Angular 5?如何访问 Angular 5 中文件上传的 HttpEvent 进度?
【发布时间】:2018-05-01 06:02:52
【问题描述】:

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

这就是我正在做的事情。

//组件代码: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;
} 

//文件服务代码

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 进度?

【问题讨论】:

    标签: angular


    【解决方案1】:

    在您的文件服务代码中:

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

    //组件

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

    【讨论】:

    • 感谢@Ritwick。但是,请注意我在问题 Tool9Response 中提到的响应拦截。当 event.type 是 HttpEventType.Response 我如何使用拦截器?
    • 稍微调整一下就可以了。谢谢你。通过编辑更新您的答案。
    • 是的! event.body 是响应对象。
    • 尝试使用(event: HttpEvent&lt;Tool9Response &gt;) 进行类型检查。
    • 假设,UploadProgress 事件正在进行,然后用户想取消它?
    猜你喜欢
    • 2017-07-04
    • 2018-10-26
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2011-02-07
    相关资源
    最近更新 更多