在我在Angular 4中开发的应用程序中,用户可以将多部分文件上传到服务器中。文件很大。我需要显示文件上传过程的当前进度及其对用户的百分比,我该怎么办?
提前致谢!
由于您使用的是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
所述
你可以通过以下方式轻松实现:
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);
});
}
使用angular-load-bar库,如果你不想使用angular-load-bar库,你可以使用进程回调eq-xhrrequest.upload.onprogress。
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>
uploadDocument(file) {
return this.httpClient.post(environment.uploadDocument, file, { reportProgress: true, observe: 'events' })
}