Angular file upload progress percentage

2019-05-22 15:04发布

问题:

In my application that i am developing in Angular 4, user can upload multipart files into server. Files are large. I need to show the current progress of file upload process with it's percentage to user, how can i do it?

Thanks in advance!

回答1:

Since you are using Angular4 , it can be achieved using Listening to progress events using the new HttpClient from @angular/common/http.

Adding code from the docs,

const req = new HttpRequest('POST', '/upload/file', file, {
  reportProgress: true,
});

and then,

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

EDIT Since OP wanted to use it with angular2, should use native JavaScript XHR wrapped as an Observable as mentioned in this answer



回答2:

You can easily achieve this with:

npm i angular-progress-http

After importing the module, you can now add below it to your app.module.ts or wherever you stack your app modules in your application.

You will import this (in app.module.ts):

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

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

Still in your app.module.ts

at @NgModule

@NgModule({

  imports: [

    HttpModule,

    ProgressHttpModule
  ]
})

Then in your component file (whatever.component.ts), where you want to use it. You can place this:

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

Then implement like this:

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


回答3:

use angular-loading-bar library, if you don't want to use angular-loading-bar library you can use progress callback eq-xhrrequest.upload.onprogress.



回答4:

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:

uploadDocument(file) {

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