I have a problem with the implementation of one of my tasks, namely, I have a problem with implementing the code in Angular (TypeScript) that will validate whether a file (mainly png/jpg, but preferably any type) is not damaged in any way.
Unfortunatelly I cannot upload example of a damaged file beacuse StackOverflow correctly validate this case, but corrupted file is easy to create by opening png/jpg file as text (by visual studio code for example) and changing somet text.
At this moment I've tried to validate this case via (change) method in input type radio:
<input type="file" name="file" accept=".png, .jpg" (change)="onFileSelected($event)" required>
but I don't really know how to do it.
Thank you very much for any attempt to help
I think we can render the image in a img
tag, which has an onerror
or (error)
event, this can signal the invalid image and we can display an error message for the same.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
fileToUpload: any;
imageUrl: any;
invalid = false;
handleFileInput(file: FileList) {
this.invalid = false;
this.fileToUpload = file.item(0);
//Show image preview
let reader = new FileReader();
reader.onload = (event: any) => {
this.imageUrl = event.target.result;
};
reader.readAsDataURL(this.fileToUpload);
}
}
<hello name="{{ name }}"></hello>
<input #Image type="file" (change)="handleFileInput($event.target.files)" />
<img
width="100%"
*ngIf="imageUrl"
[src]="imageUrl"
class="image"
(error)="invalid = true"
/>
<div *ngIf="invalid">The uploaded image is corrupted</div>