1

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.

3
  • You’re setting your image [src] to url.. which is always overwritten in the reader.onload. I guess you should be using singlefile there..? Commented Nov 5, 2021 at 12:24
  • I used singlefile but it returns the following error: GET http://localhost:4200/[object%20File] 404 (Not Found) Commented Nov 5, 2021 at 12:26
  • 2
    Do you have the url you need in singlefile? Probably not. You probably want to build up an array inside the reader onload callback. Commented Nov 5, 2021 at 12:29

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

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.