I am currently utilizing Angular 6.
In my application, I have a simple input type="file"
field that passes data to an image source which displays the image I intend to upload.
The issue I am facing is that when I select an image for the first time, nothing happens. However, when I choose an image for the second time, the preview of the image appears successfully.
What could be causing this behavior? Why am I unable to see the image preview on the first selection?
Here is my HTML code:
<div class="container" class="border">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Choose File</h3>
<form (ngSubmit)="onSubmit()">
<span style="color:red;" *ngIf="message">{{message}}</span>
<input #file type="file" ngf-max-size='10' accept='image/*' name="image" (change)="preview(file)">
<img [src]="imgURL" height="200" width="200" *ngIf="imgURL">
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
And here is my TypeScript code:
export class BottomSheetComponent implements OnInit {
token = this.pzLogin.userLoginAccessToken;
public imagePath;
imgURL: any = this.pzLogin.UserLoginClaims.ImageUrl;
public message: string;
fileData = new FileReader();
constructor(
private _bottomSheetRef: MatBottomSheetRef<BottomSheetComponent>,
private http: HttpClient, private pzLogin: PrivateZoneLoginService,
private localStorageService: LocalStorageService) { }
/* openLink(event: MouseEvent): void {
this._bottomSheetRef.dismiss();
event.preventDefault();
}*/
ngOnInit() {
}
preview(event) {
if (event.files.length === 0) {
return;
}
const mimeType = event.files[0].type;
if (mimeType.match(/image\/*/) == null) {
this.message = 'Only images are supported.';
return;
}
const fileSize = event.files[0].size;
if (fileSize > 200839) {
this.message = 'Maximum upload file size 200 kb.';
return ;
}
const reader = new FileReader();
reader.readAsDataURL(event.files[0]);
reader.onload = () => {
this.imgURL = reader.result;
this.fileData = event.files;
};
}
onSubmit() {
const formData = new FormData();
formData.append('UploadedFile', this.fileData[0], this.fileData[0].name);
formData.append('token', this.token);
this.http.post('http://localhost:11111/PrivateZone/UploadUserImage', formData)
.subscribe(res => {
console.log('res' + res);
this.localStorageService.setItem('UserLoginClaims', res);
});
}
}