Вы можете использовать комбинацию @ViewChild and ElementRef
для доступа к элементу управления загрузкой файлов и сбрасывать его значение после каждой загрузки, иначе событие (change)
не сработает.
И затем вы можете использовать FileReader()
, чтобы прочитать файл в объект Image
и получить от него ширину и высоту.
Вот код ниже -
HTML-шаблон
<input type="file" #coverFilesInput (change)="onChange($event)" class="file-input" />
Upload Percent: {{percentDone}}% <br />
<ng-container *ngIf="uploadSuccess">
Upload Successful of file with size : {{size}} bytes <br>
The image height is : {{height}} <br>
The image width is : {{width}} <br>
</ng-container>
Метод onChange
onChange(evt:any){
this.percentDone = 100;
this.uploadSuccess = true;
let image:any = evt.target.files[0];
this.size = image.size;
let fr = new FileReader();
fr.onload = () => { // when file has loaded
var img = new Image();
img.onload = () => {
this.width = img.width;
this.height = img.height;
};
img.src = fr.result; // The data URL
};
fr.readAsDataURL(image);
this.imgType.nativeElement.value = ""; // clear the value after upload
}
полный код app.component.ts
import { Component, VERSION ,ViewChild,ElementRef} from '@angular/core';
import {HttpClientModule, HttpClient, HttpRequest, HttpResponse, HttpEventType} from '@angular/common/http';
@Component({
selector: 'my-app',
template: `
Version = {{version.full}} <br/>
<input type="file" #coverFilesInput (change)="onChange($event)" class="file-input" />
Upload Percent: {{percentDone}}% <br />
<ng-container *ngIf="uploadSuccess">
Upload Successful of file with size : {{size}} bytes <br>
The image height is : {{height}} <br>
The image width is : {{width}} <br>
</ng-container>
`,
})
export class AppComponent {
percentDone: number;
uploadSuccess: boolean;
size:any;
width:number;
height:number;
@ViewChild('coverFilesInput') imgType:ElementRef;
constructor(
) { }
version = VERSION
onChange(evt:any){
this.percentDone = 100;
this.uploadSuccess = true;
let image:any = evt.target.files[0];
this.size = image.size;
let fr = new FileReader();
fr.onload = () => { // when file has loaded
var img = new Image();
img.onload = () => {
this.width = img.width;
this.height = img.height;
};
img.src = fr.result; // This is the data URL
};
fr.readAsDataURL(image);
this.imgType.nativeElement.value = "";
}
}
Вот рабочая демонстрация: https://stackblitz.com/edit/angular-file-upload-hnik7q
Редактировать: вы можететакже используйте [(ngModel)]="selectedFile"
для доступа к элементу управления входным файлом и очистки его значения после проверки и загрузки без использования @ViewChild
и ElementRef
, как показано ниже -
<input type="file" #coverFilesInput (change)="onChange($event)" class="file-input" [(ngModel)]="selectedFile"/>
и в классе компонентов -
export class AppComponent {
percentDone: number;
uploadSuccess: boolean;
size:any;
width:number;
height:number;
selectedFile:any; // declare the property
constructor(
) { }
version = VERSION
onChange(evt:any){
this.percentDone = 100;
this.uploadSuccess = true;
let image:any = evt.target.files[0];
this.size = image.size;
let fr = new FileReader();
fr.onload = () => { // when file has loaded
var img = new Image();
img.onload = () => {
this.width = img.width;
this.height = img.height;
};
img.src = fr.result; // This is the data URL
};
fr.readAsDataURL(image);
this.selectedFile = ""; // clear the file here
}
}