Preview an Image before Uploading It with JavaScript

Last updated: August 28, 2026.

A client-side preview improves feedback but does not validate the upload for the server. The server must still enforce type, dimensions, and size.

Create and revoke an object URL

const input = document.querySelector('#photo');
const preview = document.querySelector('#preview');
let previewUrl;

input.addEventListener('change', () => {
  if (previewUrl) URL.revokeObjectURL(previewUrl);
  const file = input.files[0];
  if (!file || !file.type.startsWith('image/')) { preview.removeAttribute('src'); return; }
  previewUrl = URL.createObjectURL(file);
  preview.src = previewUrl;
});

window.addEventListener('pagehide', () => {
  if (previewUrl) URL.revokeObjectURL(previewUrl);
});

Keep validation server-side

  • Use accept only as a picker hint.
  • Enforce the real MIME type on the server.
  • Limit dimensions and byte size.
  • Give the preview meaningful alternative text.

Reference: MDN URL.createObjectURL reference.

admin

admin