【问题标题】:Angular file upload progress percentage [duplicate]Angular文件上传进度百分比[重复]
【发布时间】:2018-12-11 07:40:01
【问题描述】:

在我使用 Angular 4 开发的应用程序中,用户可以将多部分文件上传到服务器。文件很大。我需要向用户显示文件上传过程的当前进度及其百分比,我该怎么做?

提前致谢!

【问题讨论】:

标签: angular file file-upload multipart


【解决方案1】:

使用 angular-loading-bar 库,如果不想使用 angular-loading-bar 库,可以使用进度回调 eq-xhrrequest.upload.onprogress.

【讨论】:

    【解决方案2】:

    您可以通过以下方式轻松实现:

    npm i angular-progress-http

    导入模块后,您现在可以将其添加到您的 app.module.ts 或您在应用程序中堆叠应用程序模块的任何位置。

    您将导入这个(在 app.module.ts 中):

    import { HttpModule } from '@angular/http';
    
    import { ProgressHttpModule } from 'angular-progress-http';
    

    仍在你的 app.module.ts 中

    @NgModule

    @NgModule({
    
      imports: [
    
        HttpModule,
    
        ProgressHttpModule
      ]
    })
    

    然后在您想要使用它的组件文件 (whatever.component.ts) 中。你可以这样放置:

    import { ProgressHttp } from 'angular-progress-http';
    

    然后像这样实现:

    constructor(private http: ProgressHttp) {}
        onSubmit(): void {
            const _formData = new FormData();
            _formData.append('title', this.title);
            _formData.append('doc', this.doc);
    
            this.http.withUploadProgressListener(progress => { console.log(`Uploading ${progress.percentage}%`); })
            .withDownloadProgressListener(progress => { console.log(`Downloading ${progress.percentage}%`); })
            .post('youruploadurl', _formData)
            .subscribe((response) => {
                console.log(response);
            });
        }
    

    【讨论】:

    • 好,thanx,试试看
    • 顺便说一句,我认为console.log('Uploading ${progress.percentage}%') 有点错误,它总是会记录0 还是会在控制台记录每个进度更改?
    • 是的,它将在控制台记录每个进度更改。您可以轻松地在视图中使用它。
    • 如果没有连接,百分比进度总是返回 NaN,如果有连接,则返回 100。如何从 0、1、2、50 到 100% 跟踪整个进度百分比? @tolulopeowolabi
    【解决方案3】:

    Gajender.service.ts

     import { Injectable } from '@angular/core';
     import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '@angular/common/http';
     import {Observable} from "rxjs";
    
          constructor(private http: HttpClient) {
          }
    
           uploadFileData(url: string, file: File): Observable<HttpEvent<any>> {
    
            let formData = new FormData();
            let user = {
              name : 'Gajender'
            }
            formData.append('file', file);
            formData.append("user", JSON.stringify(user)); 
    
            let params = new HttpParams();
    
            const options = {
              params: params,
              reportProgress: true,
            };
    
            const req = new HttpRequest('POST', url, formData, options);
            return this.http.request(req);
          }
    

    user.component.ts

    constructor( private gajender: Gajender) { }
      @ViewChild('selectfile') el:ElementRef;   //in html we make variable of selectfile
      progress = { loaded : 0 , total : 0 };
    
    uploadFile = (file) => {
        var filedata = this.el.nativeElement.files[0];
        this.gajender.uploadFileData('url',filedata)
        .subscribe(
          (data: any) => { 
            console.log(data);
            if(data.type == 1 && data.loaded && data.total){
              console.log("gaju");
              this.progress.loaded = data.loaded;
              this.progress.total = data.total;
            }
            else if(data.body){
              console.log("Data Uploaded");
              console.log(data.body);
            }
    
           },
          error => console.log(error) 
        )
    

    user.component.html

    <form enctype="multipart/form-data"  method="post">
      <input type='file' [(ngModel)]="file" name="file" #selectfile >
      <button type="button" (click)="uploadFile(file)">Upload</button>
    </form>
    Progress
    <progress [value]=progress.loaded  [max]=progress.total>
    </progress>
    

    【讨论】:

    • 请使用您在示例代码中使用的对象的正确命名约定。
    【解决方案4】:
    uploadDocument(file) {
    
        return this.httpClient.post(environment.uploadDocument, file, { reportProgress: true, observe: 'events' })
    }
    

    【讨论】:

    • 请考虑添加 cmets 和解释。这将帮助您的读者理解您的代码。 How to Answer
    【解决方案5】:

    简单我们可以使用--

     upload(formData) {
    return this.http.post<any>(api - url, formData, {
      reportProgress: true,
      observe: 'events'
    }).pipe(
      map((event: HttpEvent) => {
        if (event.type === HttpEventType.UploadProgress) {
          const percentDone = Math.round(100 * event.loaded / event.total);
          return { status: 'progress', message: percentDone };
        }
        if (event.type === HttpEventType.Response) {
          return event.body;
        }
      }),
      catchError(this.handleError)
    );
    

    }

    【讨论】:

    • upload()的返回类型是什么
    【解决方案6】:

    这适用于 Angular 9 和 10(注意 observe: 'events'

    const headers = new HttpHeaders({
            'Content-Type': 'application/json',
            Accept: 'application/json',
            Authorization: token
          }))
    const formData = new FormData();
    formData.append('file_param_name', file, file.name);
    
    this.httpClient.post(url, formData, {
        headers,
        reportProgress: true,
        observe: 'events'
    }).subscribe(resp => {
        if (resp.type === HttpEventType.Response) {
            console.log('Upload complete');
        }
        if (resp.type === HttpEventType.UploadProgress) {
            const percentDone = Math.round(100 * resp.loaded / resp.total);
            console.log('Progress ' + percentDone + '%');
        } 
    });
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2014-03-05
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 2021-03-13
      • 1970-01-01
      相关资源
      最近更新 更多