Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular/TS – validation if file is corrupted/broken

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

>Solution :

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.

TS:

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);
  }
}

HTML:

<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>

Stackblitz Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading