How do you preview an uploaded image in the browser before form submission using JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you preview an uploaded image in the browser before form submission using JavaScript?

message-square
0

To preview a selected image before submitting a form in JavaScript, listen to the change event on <input type="file" accept="image/*">, grab the selected File from input.files[0], generate a temporary local URL using URL.createObjectURL(file), set it as an <img> element’s .src, and revoke previous object URLs via URL.revokeObjectURL() to prevent memory leaks.


1. Instant Image Preview with URL.createObjectURL()

URL.createObjectURL(file) creates a blob: URL pointing directly to the File in memory without converting binary image bytes into a large base64 string, making previews fast even for large photos:

// Preview a selected image inside an <img> tag before form submission
function bindImagePreview(fileInputId, previewImgId, maxBytes = 5 * 1024 * 1024) {
  const inputEl = document.getElementById(fileInputId);
  const previewEl = document.getElementById(previewImgId);
  if (!(inputEl instanceof HTMLInputElement) || !(previewEl instanceof HTMLImageElement)) {
    return;
  }

  let activeObjectUrl = null;

  inputEl.addEventListener("change", () => {
    if (activeObjectUrl) {
      URL.revokeObjectURL(activeObjectUrl);
      activeObjectUrl = null;
    }

    const file = inputEl.files && inputEl.files[0];
    if (!file) {
      previewEl.removeAttribute("src");
      previewEl.hidden = true;
      return;
    }

    if (!file.type.startsWith("image/") || file.size > maxBytes) {
      inputEl.value = "";
      previewEl.removeAttribute("src");
      previewEl.hidden = true;
      console.warn("Invalid image type or file size exceeds limit:", file.name);
      return;
    }

    activeObjectUrl = URL.createObjectURL(file);
    previewEl.src = activeObjectUrl;
    previewEl.alt = `Preview of ${file.name}`;
    previewEl.hidden = false;
  });
}

bindImagePreview("avatar-input", "avatar-preview");
  • Fast and memory-friendly: Avoids turning binary image bytes into large base64 strings before upload.
  • Revokes stale URLs: Frees the previous blob: URL whenever the user picks a different file or clears the input.
  • Client-side type & size guard: Checks file.type.startsWith("image/") and file.size before showing the preview (still validate on the server on submit).

2. Submitting the File with the Form via FormData

Once previewed, the <input type="file" name="avatar"> still holds the File selection for a standard form submit, or you can append it to a FormData instance inside a submit handler for fetch() uploads:

// Submit the form including the selected image file via FormData and fetch()
function attachImageFormSubmit(formId, fieldName = "avatar") {
  const formEl = document.getElementById(formId);
  if (!(formEl instanceof HTMLFormElement)) {
    return;
  }

  formEl.addEventListener("submit", async (event) => {
    event.preventDefault();

    const formData = new FormData(formEl);
    const file = formData.get(fieldName);

    if (!(file instanceof File) || file.size === 0) {
      console.warn("Please select an image before submitting.");
      return;
    }

    const response = await fetch(formEl.action || "/api/upload", {
      method: formEl.method || "POST",
      body: formData
    });

    if (!response.ok) {
      throw new Error(`Upload failed with HTTP ${response.status}`);
    }

    const result = await response.json();
    console.log("Upload complete:", result);
  });
}

attachImageFormSubmit("profile-form", "avatar");
  • new FormData(formEl): Automatically collects named form inputs and attached File objects for multipart/form-data submission.
  • No manual Content-Type header: Lets the browser set the multipart/form-data boundary header automatically.

3. Common Traps to Avoid

Previewing uploaded images before form submission often runs into a few pitfalls:

  • Leaking object URLs on repeated file selections: Calling URL.createObjectURL() on every change event without calling URL.revokeObjectURL() on the previous URL retains blob references in memory until the document unloads.
  • Trusting only accept="image/*" or file.type for security: Users can bypass file-picker filters or rename files—always validate MIME type, file size, and image integrity on the server when processing uploads.
  • Resetting the file input after change without clearing the preview: If you clear input.value = "" on an invalid file, also hide/reset the <img> preview so stale UI does not remain visible.

TL;DR: Listen for change on <input type="file">, validate file.type and file.size, set img.src = URL.createObjectURL(file) for the preview, revoke old object URLs with URL.revokeObjectURL(), and submit the file with FormData.

Are you previewing a single avatar image, rendering multiple thumbnails for input[multiple], or submitting the image with extra form fields via fetch()?