Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

html - Preview multiple image before upload file in Angular

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]);
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...