我想在html
中显示文件上传进度,但是在控制台中看不到它却没有显示。可能是这种行为的原因?
如果我执行console.log(this.progress)
,则可以在控制台中看到它,但是不能在html {{progress}}
内看到
html
<div class="document-upload-tab">
<button mat-button (click)="select()">
<img src="assets/svg/cloud-upload.svg" /> {{text}}
</button>
<br/>
<input type="file" id="fileUpload" name="fileUpload" accept="application/pdf,application/vnd.ms-excel" style="display:none;"
/>
<button mat-raised-button (click)="save()">
Save
</button>
</div>
<ng-container *ngIf="fileSelected">
{{progress}}percentage
<mat-progress-bar [value]="progress"></mat-progress-bar>
</ng-container>
ts
select() {
console.log('here');
const fileUpload = document.getElementById(
'fileUpload'
) as HTMLInputElement;
console.log(fileUpload);
fileUpload.onchange = () => {
this.file = fileUpload.files.item(0);
};
fileUpload.click();
}
save() {
console.log(this.file);
this.fileSelected = true;
this.uploadfile(this.file)
.then(res => {
console.log(res);
})
.catch(err => {
this.toastr.info('', 'Error while uploading file!', {
positionClass: 'toast-top-center',
closeButton: true
});
});
}
uploadfile(file) {
console.log(file);
const bucket = new S3({
accessKeyId: environment.accessKeyId,
secretAccessKey: environment.secretAccessKey,
region: environment.region
});
const params = {
Bucket: environment.Bucket,
Key: file.name,
Body: file
};
const options = {
// Part Size of 10mb
partSize: 10 * 1024 * 1024,
queueSize: 1,
// Give the owner of the bucket full control
ACL: 'bucket-owner-full-control'
};
const upload = bucket
.upload(params, options)
.on('httpUploadProgress', function(event) {
this.progress = Math.round((event.loaded / event.total) * 100);
console.log(this.progress);
this.toastr.info(this.progress);
return event;
});
const promise = upload.promise();
return promise;
}
答案 0 :(得分:2)
将 httpUploadProgress 回调函数更改为Arrow函数。看起来没有绑定此类。
const upload = bucket.upload(params, options)
.on('httpUploadProgress', (event) => { // change here
this.progress = Math.round((event.loaded / event.total) * 100);
console.log(this.progress);
this.toastr.info(this.progress);
return event;
});
答案 1 :(得分:1)
据我所知,问题是* ngIf,请尝试删除* ngIf并查看其是否呈现,
<ng-container>
<h1>{{progress}}percentage</h1>
<mat-progress-bar [value]="progress"></mat-progress-bar>
</ng-container>
答案 2 :(得分:1)
您可以使用ChangeDetectorRef
来手动调用更改检测:
TS
import {ChangeDetectorRef} from "@angular/core"
constructor(private ref: ChangeDetectorRef) {
}
uploadfile(file) {
...
const upload = bucket
.upload(params, options)
.on('httpUploadProgress', (event) => {
this.progress = Math.round((event.loaded / event.total) * 100);
this.ref.detectChanges(); <========= here
...
return event;
});
const promise = upload.promise();
return promise;
}