As a newcomer to Angular, I am currently working on a feature that involves selecting multiple files and displaying their previews before uploading them to the server.
While my code works correctly when individual files are selected one at a time, it fails to render all images when multiple files are chosen simultaneously. Upon further inspection using console.log, I noticed that the reader.result for all files except the last one is null, even though the reader.onload function is being executed (with the file object being added to the array without the image URL).
I aim to implement a way to remove selected files while preserving both the files themselves and their corresponding image URLs in a FileWithImage object to maintain the correct order of previews.
In my component.ts file:
onFilesSelected(event: any): void {
this.selectedFiles = event.target.files;
for (let i = 0; i < this.selectedFiles.length; i++) {
let fileWithImage: FileWithImage = {
imageUrl: '',
file: this.selectedFiles[i],
};
var reader = new FileReader();
reader.readAsDataURL(fileWithImage.file);
reader.onload = (event) => {
fileWithImage.imageUrl = reader.result;
console.log(fileWithImage.file.name);
console.log(fileWithImage.imageUrl);
this.filesWithImages.push(fileWithImage);
};
}
}
And in my component.html file (for selecting and displaying images):
<button
type="button"
mat-raised-button
(click)="fileInput.click()"
class="button"
>
Choose File
</button>
<input
hidden
(change)="onFilesSelected($event)"
#fileInput
type="file"
accept="image/*"
multiple="multiple"
/>
<div *ngFor="let file of filesWithImages" class="images">
<img
[src]="file.imageUrl"
height="10%"
width="10%"
*ngIf="file.imageUrl"
/>
</div>
I have attempted solutions like using a flag to block the loop until reader.onload executes, as well as directly fetching the URL from a method:
createImageUrl(file: File): any {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
return reader.result;
};
}
But calling this method in the [src] attribute of an image tag in HTML caused my program to crash.
The primary issue seems to be why the result of the reader is null for initial files and only properly displayed for the last one. If anyone can help me identify the root cause of this problem, I would greatly appreciate it.