9

How can I preview multiple images that I have selected before uploading them in Angular?

enter image description here

I have managed to do it but only with one image, even though I select several, only one recognizes me. I think the use of *ngFor is a good alternative but I'm not sure how to raise it. Any ideas?

myComponent.html

<img *ngIf="url" [src]="url" class="rounded mb-3" width="180">
<input type="file" multiple (change)="detectFiles($event)">

myComponent.ts

detectFiles(event) {
this.selectedFiles = event.target.files;
if (event.target.files && event.target.files[0]) {
  var reader = new FileReader();
  reader.onload = (event: any) => {
    this.url = event.target.result;
  }
  reader.readAsDataURL(event.target.files[0]);
}
}

1 Answer 1

36

As shown in this stackblitz, you can store the image URLs in an array and display them with ngFor:

<div>
    <img *ngFor="let url of urls" [src]="url" class="rounded mb-3" width="180">
</div>
<input type="file" multiple (change)="detectFiles($event)">

The array of URLs is filled in detectFiles:

export class AppComponent {

  urls = new Array<string>();

  detectFiles(event) {
    this.urls = [];
    let files = event.target.files;
    if (files) {
      for (let file of files) {
        let reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        }
        reader.readAsDataURL(file);
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works but hangs dom with high resolution image and number of images are high may be due huge base64 data. @ConnorsFan can you please suggest any resolution for this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.