Course contentsShow
← Web Development
Lesson 2709 of 2,98248. File Uploads and HandlingFree lesson

Handling Multiple Image Previews

Loop through FileList when multiple files are selected and generate individual preview elements for each image.

Handling Multiple Image Previews

What you'll learn: How to generate individual preview elements for each image when users select multiple files at once.

When users select multiple images using a file input with the multiple attribute, the browser provides a FileList object containing all selected files. To show previews for each one, you need to loop through this list and create separate preview elements for each image.

The Core Technique

Think of a FileList as an array-like collection of File objects. While it looks like an array, it doesn't have methods like .forEach() built in (though modern browsers support it). The classic approach is using a standard for loop or converting it to a proper array.

For each file in the list, you'll:

  1. Create a FileReader instance
  2. Read the file as a Data URL
  3. Generate a preview element (like an <img>) in your DOM
  4. Set the src to the Data URL when reading completes

Practical Pattern

const input = document.getElementById('file-input');
const previewContainer = document.getElementById('preview-container');

input.addEventListener('change', (event) => {
  previewContainer.innerHTML = ''; // Clear previous previews
  const files = event.target.files;

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const reader = new FileReader();

    reader.onload = (e) => {
      const img = document.createElement('img');
      img.src = e.target.result;
      img.style.maxWidth = '150px';
      img.style.margin = '10px';
      previewContainer.appendChild(img);
    };

    reader.readAsDataURL(file);
  }
});

Each iteration creates its own FileReader, ensuring all images load independently and asynchronously without interfering with each other.

Key Takeaway: Loop through the FileList using a standard for loop, create a separate FileReader for each file, and dynamically generate individual preview elements as each read operation completes.