Preview an Image before Uploading It with JavaScript

Last updated: August 29, 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.

Keep preview and upload validation separate

An object URL previews local bytes without reading the whole image into a data URL, but it does not make the file safe. The server must still detect type, enforce limits, and generate its own filename.

Test choosing a second file, clearing the input, selecting a non-image, and leaving the page. Revoke old object URLs so repeated selections do not retain unnecessary browser resources.

  • Use accept only as a picker hint.
  • Provide meaningful preview alt text.
  • Reject excessive dimensions on the server.

Progressive enhancement matters: preserve semantic HTML and a usable server-side path. Test keyboard operation, failure states, and rapid repeated actions rather than only the ideal mouse interaction.

Continue with secure upload pipeline, EXIF rotation, and PHP upload guide.

Practical implementation check

Keep the underlying HTML usable before JavaScript runs, then add behavior as an enhancement. Test rapid repeated interaction, keyboard use, a slow or failed network request, and navigation away from the page. Remove temporary listeners or resources when appropriate, and ensure visible status changes are also available to assistive technology.

Reference: MDN URL.createObjectURL reference.

admin

admin