Home > Mobile >  Multiple Image Upload in Angular shows one image repeatedly instead of all images
Multiple Image Upload in Angular shows one image repeatedly instead of all images

Time:11-08

I am trying to upload multiple images by storing them in an array. Each image is stored as a file object like this:

enter image description here

I want to send my images as File objects, not as base64. However when I try to preview the images, only the last selected image shows repeatedly (screenshot below):

enter image description here

I want all selected images to preview, not just one image 4 times.

Working Stackblitz!

Here is my code:

onSelectFile(event) {
    this.file = event.target.files && event.target.files.length
    if (this.file > 0 && this.file < 5) {
      let i: number = 0;
      for (const singlefile of event.target.files) {
        var reader = new FileReader();
        reader.readAsDataURL(singlefile); 
        this.urls.push(singlefile);
        this.cf.detectChanges()
        i  ;
        console.log(this.urls)
        reader.onload = (eventFile: any) => {
          this.url = eventFile.target.result;
          this.cf.detectChanges()
        }
        //console.log(singlefile)
      };
    }
    else {
      this.toast.error('No More than 4 images', 'Upload Images')
    }
  }

My HTML:

<div class="preview-media" data-max-image="4" style="margin-top: -20px; width: auto;
 height:auto; display: flex; flex-wrap: wrap; object-fit: cover;">
   <ng-container *ngFor="let singlefile of urls">
     <img [src]="url" style="flex-grow: 1; flex-direction: row; flex-wrap: wrap;
       width: 50%; height: auto; object-fit: cover;">
   </ng-container>
</div>

Any help is greatly appreciated. Thanks.

CodePudding user response:

Based on MikeOne's reply, I created a separate array and pushed the images into that array. Then I called the new array in my html and it worked. Thank You MikeOne

Solution: Updated StackBlitz!

  • Related