在我用 Angular 4 开发的应用程序中,用户可以将多部分文件上传到服务器。文件很大。我需要向用户显示文件上传过程的当前进度及其百分比,我该怎么做?
提前感谢!
适用于 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 + '%');
}
});
uploadDocument(file) {
return this.httpClient.post(environment.uploadDocument, file, { reportProgress: true, observe: 'events' })
}
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)
)
用户组件.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>
您可以通过以下方式轻松实现此目的:
npm i angular-progress-http
导入模块后,现在可以将其添加到 app.module.ts 下方或应用程序中堆叠应用模块的任何位置。
您将导入以下内容(在 app.module.ts 中):
import { HttpModule } from '@angular/http';
import { ProgressHttpModule } from 'angular-progress-http';
仍在您的应用程序中。
在@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);
});
}
我们可以使用的简单 --
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)
);
}
使用角度加载栏库,如果不想使用角度加载栏库,可以使用进度回调eq-xhrrequest.upload.onprogress.