Angular文件上传进度百分比

时间:2017-10-31 11:33:45

标签: angular file file-upload multipart

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

提前致谢!

7 个答案:

答案 0 :(得分:21)

由于您使用的是Angular4,因此可以使用 @angular/common/http.

中的新HttpClient使用 Listening to progress 事件来实现

从文档中添加代码,

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

修改 由于OP希望将其与angular2一起使用,因此应使用本机JavaScript XHR包装为Observable,如 answer

中所述

答案 1 :(得分:7)

这适用于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 + '%');
    } 
});

答案 2 :(得分:1)

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

npm i angular-progress-http

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

您将导入此内容(在app.module.ts中):

List<Point> list;
list.OrderBy(p => p.x).ThenBy(q => q.y);

仍然在你的app.module.ts

@NgModule

import { HttpModule } from '@angular/http';

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

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

@NgModule({

  imports: [

    HttpModule,

    ProgressHttpModule
  ]
})

然后像这样实施:

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

答案 3 :(得分:0)

使用angular-load-bar库,如果你不想使用angular-load-bar库,你可以使用进度回调 EQ-xhrrequest.upload.onprogress。

答案 4 :(得分:0)

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>

答案 5 :(得分:0)

uploadDocument(file) {

    return this.httpClient.post(environment.uploadDocument, file, { reportProgress: true, observe: 'events' })
}

答案 6 :(得分:0)

我们可以简单地使用-

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

}