Preview multiple image before upload file in Angular

前端 未结 2 546
予麋鹿
予麋鹿 2020-12-16 03:40

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

I have managed to do it but only with one image, even though I sele

相关标签:
2条回答
  • 2020-12-16 04:14

    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);
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-16 04:15

    we can use *ngFor like so:

    <div *ngFor="let img of arrayOfImg; let i = index">
          <img [src]="img" class="rounded mb-3" width="180">
    </div>
    

    I added the index because its useful to have sometimes, if the array isnt just simply a string array, instead a json or object array you might have to do this:

    [src]="img.url"

    I am not sure how to upload/select the files for upload but I would assume when you select them from the computer and/or URL that you simply add their URL to an array

    0 讨论(0)
提交回复
热议问题