How to preview an image before it is uploaded in JavaScript ?

Here’s how to preview an image before uploading it using JavaScript, with examples and best practices:

Step-by-Step Guide

1. HTML Setup

Create a file input and an <img> element for the preview:

<input type="file" accept="image/*" id="uploadInput">
<img id="preview" src="#" alt="Image preview" style="display: none;">

2. JavaScript Logic

Use URL.createObjectURL() for efficient preview (recommended):

const uploadInput = document.getElementById('uploadInput');
const preview = document.getElementById('preview');
let currentObjectUrl = null;

uploadInput.addEventListener('change', function(e) {
  const file = e.target.files[0];

  // Validate the file is an image
  if (!file || !file.type.startsWith('image/')) {
    preview.style.display = 'none';
    alert('Please select an image file.');
    return;
  }

  // Revoke previous object URL to free memory
  if (currentObjectUrl) {
    URL.revokeObjectURL(currentObjectUrl);
  }

  // Create a temporary URL for the file
  currentObjectUrl = URL.createObjectURL(file);
  preview.src = currentObjectUrl;
  preview.style.display = 'block';

  // Clean up memory after the image loads
  preview.onload = function() {
    URL.revokeObjectURL(currentObjectUrl); // Optional but recommended
  };
});

Alternative Method: FileReader

Use FileReader for broader compatibility (base64 encoding):

uploadInput.addEventListener('change', function(e) {
  const file = e.target.files[0];

  if (!file || !file.type.startsWith('image/')) {
    preview.style.display = 'none';
    return;
  }

  const reader = new FileReader();

  reader.onload = function(e) {
    preview.src = e.target.result;
    preview.style.display = 'block';
  };

  reader.readAsDataURL(file); // Convert to base64 string
});

Key Notes

  1. Validation
    Use file.type.startsWith('image/') to ensure the file is an image.
  2. Memory Management
    Always revoke object URLs with URL.revokeObjectURL() when they’re no longer needed.
  3. Multiple Files
    To handle multiple files:
   uploadInput.multiple = true; // Enable multi-select in HTML

   uploadInput.addEventListener('change', function(e) {
     const files = e.target.files;
     const previewContainer = document.getElementById('previewContainer');

     previewContainer.innerHTML = ''; // Clear previous previews

     Array.from(files).forEach(file => {
       if (!file.type.startsWith('image/')) return;

       const img = document.createElement('img');
       img.src = URL.createObjectURL(file);
       img.style.maxWidth = '200px';
       previewContainer.appendChild(img);
     });
   });
  1. Styling
    Hide the preview initially with display: none and show it after loading.

Comparison

MethodProsCons
URL.createObjectURLFaster (no base64 encoding)Requires manual memory cleanup
FileReaderUniversally supportedLarger data URLs (memory-intensive)

Best Practices

  • Use accept="image/*" in the input to restrict file types.
  • Always validate file types server-side (client-side checks can be bypassed).
  • For large files, consider compressing images before previewing.

Leave a Reply

Your email address will not be published. Required fields are marked *