我使用此代码将文件上传到Angular 6
。
一切正常,但是我需要在代码中添加进度条。从stackoverflow搜索之后,我在下面看到了这段代码,但对angular
或angular6
还是陌生的,我不知道如何集成它或使进度条与angular
一起使用表单提交。
this.uploader.onProgressItem = (progress: any) => {
console.log(progress['progress']);
};
this.uploader.onSuccessItem = (progress: any) => {
console.log('I receive the response file posted in API');
};
Progress Bar in ng2-file-upload in Angular 6
下面是代码
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
const URL = 'http://localhost:3000/api/upload';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'photo' });
ngOnInit() {
this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
console.log('ImageUpload:uploaded:', item, status, response);
alert('File uploaded successfully');
};
}
}
app.component.html:
<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />
<button type="button" class="btn btn-success btn-s"
(click)="uploader.uploadAll()"
[disabled]="!uploader.getNotUploadedItems().length" >
Upload an Image
</button>
答案 0 :(得分:0)
如果使用HttpClient上载文件,则可以从上载请求中检索进度状态。您基本上将拥有一个类似于以下内容的方法:
public upload(endPoint: string, payload: any): Observable<any> {
const req = new HttpRequest('POST', this.apiUrl + endPoint, payload, {reportProgress: true});
return this.http.request(req);
}
此方法返回包含上载进度的响应。然后,您可以在组件中创建一个属性,以计算上传完成的百分比:
...
if (event.type === HttpEventType.UploadProgress) {
this.percentComplete = Math.round(100 * event.loaded / event.total);
} else if (event.type === HttpEventType.Response) {
// do something with body event.body
}
...
答案 1 :(得分:0)
由于您使用的是ng2-file-upload库,因此可以利用this.uploader.queue中的进度并将其显示在html中。
uploader.queue是一个数组。如果您将其用于单个文件上传,则可以从uploader.queue [0]访问上传项,并显示进度条,即:
<div class="progress-bar progress-bar-success" [ngStyle]="{ 'width': uploader.queue[0].progress + '%', 'height': '5px' }" tooltip="{{uploader.queue[0].progress}}% uploaded" placement="bottom"></div>
在此示例中,使用引导程序4进度条类am。希望这可以帮助。