Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To preview a locally selected image in JavaScript, listen for the file input’s change event, read the selected File from input.files, and set an image element’s src to URL.createObjectURL(file). Revoke that object URL when the preview is replaced or removed. If your application specifically needs the file represented as a data URL, use FileReader.readAsDataURL() instead.

Preview a selected image with an object URL

A browser file picker gives your page a user-selected File; JavaScript does not get arbitrary access to a person’s local files by pathname. The file input’s value does not expose the real local path. Use the file object in input.files as the preview source instead. MDN documents both object URL and data URL approaches in its guide to using files from web applications.

This complete example handles an empty selection, rejects files whose reported MIME type does not begin with image/, updates the preview’s alternative text, and releases an earlier object URL when the user picks another file.

<label for="image-file">Choose an image to preview</label>
<input id="image-file" type="file" accept="image/*">
<p id="preview-status" role="status">No image selected.</p>
<img id="image-preview" alt="" hidden>

<script>
  const input = document.querySelector("#image-file");
  const preview = document.querySelector("#image-preview");
  const status = document.querySelector("#preview-status");
  let previewUrl = null;

  input.addEventListener("change", () => {
    const file = input.files && input.files[0];

    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
      previewUrl = null;
    }

    if (!file) {
      preview.removeAttribute("src");
      preview.alt = "";
      preview.hidden = true;
      status.textContent = "No image selected.";
      return;
    }

    if (!file.type.startsWith("image/")) {
      preview.removeAttribute("src");
      preview.alt = "";
      preview.hidden = true;
      status.textContent = "Please choose an image file.";
      return;
    }

    previewUrl = URL.createObjectURL(file);
    preview.src = previewUrl;
    preview.alt = `Preview of ${file.name}`;
    preview.hidden = false;
    status.textContent = `Previewing ${file.name}.`;
  });

  function clearPreview() {
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
      previewUrl = null;
    }
    input.value = "";
    preview.removeAttribute("src");
    preview.alt = "";
    preview.hidden = true;
    status.textContent = "No image selected.";
  }
</script>

The input’s accept="image/*" attribute guides the file picker toward image files; it is not a complete validation or security check. The JavaScript check above is useful for a clear preview error, but the browser-provided file type metadata should not be treated as a guarantee about the file’s contents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 4x optical zoom with a 27mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen with 2 AA alkaline batteries for convenient on-the-go use

What the object URL does

URL.createObjectURL(file) creates a URL that points to the selected File or another Blob. Assign it to img.src and the browser can display that image. Each object URL is unique. Keep the URL while its preview is in use, then call URL.revokeObjectURL(url) when you replace or remove the preview. This matters particularly in interfaces where users can repeatedly select, remove, or reorder images.

Use FileReader when you need a data URL

If the application needs the file contents represented as a data URL, use FileReader.readAsDataURL(file). The read is asynchronous; when it finishes, the result is available from the reader’s result property. MDN documents this method at readAsDataURL() and describes the reader at FileReader.

const input = document.querySelector("#image-file");
const preview = document.querySelector("#image-preview");
const status = document.querySelector("#preview-status");

input.addEventListener("change", () => {
  const file = input.files && input.files[0];
  if (!file) {
    preview.removeAttribute("src");
    preview.hidden = true;
    status.textContent = "No image selected.";
    return;
  }
  if (!file.type.startsWith("image/")) {
    preview.removeAttribute("src");
    preview.hidden = true;
    status.textContent = "Please choose an image file.";
    return;
  }

  const reader = new FileReader();
  reader.addEventListener("load", () => {
    if (typeof reader.result === "string") {
      preview.src = reader.result;
      preview.alt = `Preview of ${file.name}`;
      preview.hidden = false;
      status.textContent = `Previewing ${file.name}.`;
    }
  });
  reader.addEventListener("error", () => {
    preview.removeAttribute("src");
    preview.hidden = true;
    status.textContent = "The selected file could not be read.";
  });
  reader.readAsDataURL(file);
});

Choose between the two approaches based on what the rest of your code needs:

Approach Preview source Choose it when Cleanup to consider
Object URL A URL returned by URL.createObjectURL(file). You simply need to point an image element at a selected File or Blob. Revoke the object URL with URL.revokeObjectURL() when the preview is replaced or removed.
FileReader data URL The reader’s result after readAsDataURL(file) completes. Your application specifically needs the file represented as a data URL. Handle asynchronous completion and read errors; this method does not create an object URL to revoke.

The cited documentation supports both techniques, not a general performance ranking. Do not choose one on the assumption that it is categorically faster or more memory-efficient.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 5x optical zoom with a 28mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen and a rechargeable lithium-ion battery for on-the-go use

Preview multiple selected images

Add multiple to the input and iterate through its FileList. For each accepted file, make an image element and retain its URL so it can be revoked when that preview is deleted. This example clears and releases the previous batch before displaying the new selection.

<label for="image-files">Choose images</label>
<input id="image-files" type="file" accept="image/*" multiple>
<p id="gallery-status" role="status">No images selected.</p>
<div id="gallery"></div>

<script>
  const input = document.querySelector("#image-files");
  const gallery = document.querySelector("#gallery");
  const status = document.querySelector("#gallery-status");
  let previewUrls = [];

  function clearGallery() {
    for (const url of previewUrls) URL.revokeObjectURL(url);
    previewUrls = [];
    gallery.replaceChildren();
  }

  input.addEventListener("change", () => {
    clearGallery();
    const files = Array.from(input.files || []);
    const images = files.filter(file => file.type.startsWith("image/"));

    if (images.length === 0) {
      status.textContent = files.length
        ? "No supported image files were selected."
        : "No images selected.";
      return;
    }

    for (const file of images) {
      const url = URL.createObjectURL(file);
      previewUrls.push(url);
      const image = document.createElement("img");
      image.src = url;
      image.alt = `Preview of ${file.name}`;
      gallery.append(image);
    }
    status.textContent = `Showing ${images.length} image preview(s).`;
  });
</script>

For an interface that removes one image at a time, associate each image with its own URL and revoke that URL when its preview is removed. Do not revoke a URL while the corresponding preview is still being used.

Accept dropped files using the same preview flow

A drag-and-drop zone can feed files into the same general preview logic: obtain the dropped files from the drop event, filter them, and create previews. Keep a real file input available as a picker alongside the drop area rather than making drag and drop the only route. MDN covers file handling for this pattern in its file drag and drop guide.

<label for="drop-image">Choose an image</label>
<input id="drop-image" type="file" accept="image/*">
<div id="drop-zone">Drop images here</div>
<p id="drop-status" role="status">No image selected.</p>
<div id="drop-previews"></div>

<script>
  const picker = document.querySelector("#drop-image");
  const zone = document.querySelector("#drop-zone");
  const status = document.querySelector("#drop-status");
  const container = document.querySelector("#drop-previews");
  let urls = [];

  function showFiles(fileList) {
    for (const url of urls) URL.revokeObjectURL(url);
    urls = [];
    container.replaceChildren();

    const files = Array.from(fileList || []);
    const images = files.filter(file => file.type.startsWith("image/"));
    if (images.length === 0) {
      status.textContent = files.length
        ? "No supported image files were selected."
        : "No image selected.";
      return;
    }

    for (const file of images) {
      const url = URL.createObjectURL(file);
      urls.push(url);
      const image = document.createElement("img");
      image.src = url;
      image.alt = `Preview of ${file.name}`;
      container.append(image);
    }
    status.textContent = `Showing ${images.length} image preview(s).`;
  }

  picker.addEventListener("change", () => showFiles(picker.files));
  zone.addEventListener("dragover", event => event.preventDefault());
  zone.addEventListener("drop", event => {
    event.preventDefault();
    showFiles(event.dataTransfer.files);
  });
</script>

The drop handler prevents the browser’s default drop behavior and passes the transferred files to the same routine used by the picker. The examples replace the previous previews as a batch; if your interface should append dropped files instead, retain existing entries and their URLs rather than clearing them.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Digital Camera, Latest FHD 1080P Digital Camera for Teens with SD Card Anti Shake Point and Shoot Cameras Portable 16X Zoom Compact Small Cameras for Kids Boys Girls Seniors with Wrist Strap
  • Latest Digital Camera Built-in Fill Light : This compact digital camera is paired with a powerful CMOS processor and image stabilization to help you take & record the most exciting moments in 44 MP quality images & FHD 1080P quality videos anywhere, anytime. Plus, there is also a built-in fill light to help you take high quality pictures even in low light&dark settings, making this the perfect camera for all indoors/outdoors situations.
  • Long-Lasting Battery Life & 16X Digital Zoom :This point and shoot camera will retain its battery charge even after long use. The controls and functions are easy to operate making this the perfect choice for children, teens and younger. This kids camera supports 16x digital zoom, you can zoom in or out the subject by pressing the W/T button for taking still photos to zoom in or out on distant objects and capture all the details you need.
  • Multifunctional & Portable Digital Camera: This cheap digital camera is slim enough to fit in your pocket. You'll easily be able to take it with you on all your indoor/outdoor activities and adventures and ideal for beginners, children and teenagers. This kids digital camera is equipped with 20 filters, anti-shaking, self-timer, continuous shooting, date stamp, time-lapse recording, smile capture, internal MIC and speaker (recording sound videos), great for your daily photography needs.
  • WEBCAM & PAUSE FUNCTION : More than just a FHD 1080p digital camera, it also works as a webcam for video calls and vlogging. Connect the camera to the computer, press shutter and power button at the same time and the camera will automatically turn on webcam mode for all your video calling and live streaming needs. The pause function allows you to pause when seeing playback videos.
  • A Must Have Photography Device : This digital camera with SD card made from high-quality materials, this retro camera is safe and durable. Perfect for all ages to develop & improve their photographic abilities and observation skills. Our dedicated and experienced 24/7 support team is available for all after purchase troubleshooting, questions and technical help.

Make the preview understandable and recoverable

  • Associate visible label text with the file input, as in the examples, and leave the picker available even when you provide a drop zone.
  • Give the displayed image meaningful alternative text, and put selection errors and empty-state messages in text rather than relying on appearance alone.
  • Tell users how to replace or clear a preview. If you add a clear button, call URL.revokeObjectURL(), remove the image source, and update the status.
  • Show a useful message when a selection contains no supported images instead of silently leaving an old preview visible.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting image previews

The preview does not appear

Check that the handler reads input.files[0] after the change event, and that it assigns the resulting object URL or completed reader result to the intended image element’s src. Check that the image element is not still hidden and that the code is selecting the correct element.

Choosing another file leaves the old image or resources around

When replacing an object-URL preview, revoke the previous URL and then set the new source. When clearing it, remove the source and hide the image as well as revoking the URL. For a gallery, keep a URL for each preview and release each URL when its image is removed.

The picker seems to allow a non-image file

accept="image/*" is a picker hint, not a complete validation check. Inspect the selected file’s type metadata for the preview experience and show a message for unsupported selections. Do not describe that client-side check as a security guarantee.

The FileReader version stays empty

readAsDataURL() works asynchronously. Set the image source after the reader’s load event, using reader.result, and handle its error event so a failed read produces an understandable message.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 5x optical zoom with a 28mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen and a rechargeable lithium-ion battery for on-the-go use

Drag and drop navigates away instead of showing a preview

Prevent the default behavior in the drop event, then read files from event.dataTransfer.files and pass them to the preview routine. Keep the picker route available for users who do not use drag and drop.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a way to preview a visitor’s locally selected upload. If your actual task is to capture a web page by URL—for example, to create a page screenshot for an application—one GET request can save the result. See the ScreenshotNeo documentation for request options and response details.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Cookie banners, popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. These website-capture features do not replace the local-file preview code above. Learn about ScreenshotNeo, or sign up for 1,000 free screenshots a month with no card.

Sources and scope

The file-handling guidance here is grounded in MDN documentation accessed September 29, 2026: Using files from web applications, the file input reference, the File API, FileReader, readAsDataURL(), and file drag and drop. Browser support can change; consult current compatibility information if you need a browser- and version-specific support matrix.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can JavaScript preview an image by giving it a local file path?

No. Use a file selected by the user, obtained from a file input or a drop operation; a page does not get arbitrary access to local files by pathname.

Does the preview code upload the selected image?

No. The examples display a selected file in the page. They do not submit or upload it.

Quick Recap

SaleBestseller No. 1
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$99.99
SaleBestseller No. 2
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$139.99
Bestseller No. 4
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$139.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.