Angular文件上传进度百分比

问题描述 投票:9回答:5

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

提前致谢!

angular file file-upload multipart
5个回答
25
投票

由于您使用的是Angular4,因此可以使用Listening to progress中的新HttpClient使用@angular/common/http.事件来实现

从文档中添加代码,

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
投票

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

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

0
投票

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


0
投票

Gajendrksrviskts

 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>

0
投票
uploadDocument(file) {

    return this.httpClient.post(environment.uploadDocument, file, { reportProgress: true, observe: 'events' })
}
© www.soinside.com 2019 - 2024. All rights reserved.