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

To preview an image before uploading it, read the first selected File from an <input type="file">, create a temporary object URL with URL.createObjectURL(file), and assign that URL to an <img> element. The browser displays the local image without sending it to your server. Release each object URL with URL.revokeObjectURL() when the preview is replaced or removed.

This pattern is lightweight, works for single or multiple files, and can be reused for drag-and-drop. The complete examples below validate the selection, handle errors, preserve accessibility, and clean up browser resources.

Basic single-image preview

Start with a labeled file control and an image that is hidden until a valid selection exists. The accept attribute guides the picker, but it is not a complete security check; JavaScript should still inspect the selected file and your server must validate the upload independently.

<label for="image-input">Choose an image</label>
<input id="image-input" type="file" accept="image/*">
<p id="image-error" role="alert" hidden></p>
<img id="image-preview" alt="Selected image preview" hidden>

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

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

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

  preview.removeAttribute("src");
  preview.hidden = true;
  error.hidden = true;
  error.textContent = "";

  if (!file) {
    return;
  }

  if (!file.type.startsWith("image/")) {
    error.textContent = "Choose an image file.";
    error.hidden = false;
    return;
  }

  previewUrl = URL.createObjectURL(file);
  preview.src = previewUrl;
  preview.hidden = false;
});

function clearImagePreview() {
  if (previewUrl) {
    URL.revokeObjectURL(previewUrl);
    previewUrl = undefined;
  }
  preview.removeAttribute("src");
  preview.hidden = true;
  input.value = "";
}
</script>

The files property is a FileList; optional chaining makes an empty selection safe. A File supplies metadata such as name, size, and type. URL.createObjectURL(file) returns a blob URL that can be used as an image source. See MDN’s Using files from web applications and File references.

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.
#1 Best Overall
Sale
acer SD Card Reader USB C, Dual Slots USB Type C to Micro SD Card Adapter
  • 【Ultra-Fast Data Transfer】Experience blazing-fast 5Gbps data transfer with this USB 3.0 SD Card Reader, ensuring quick and efficient file transfers for photos, videos, and other media. Backward-compatible with USB 2.0 for added flexibility. Easily review and transfer data from security cameras, wildlife monitors, or car cameras, gopro without hassle(📌Note:only reads and transfers data from the SD and TF card, not directly connect to the camera)
  • 【Simultaneous Dual-Card】Save time and boost productivity with dual card slots that allow simultaneous reading and writing on both microSD and SD cards. USB-A and USB-C dual header design makes the micro SD Card Reader perfect for photographers, video editors who need quick and efficient file management(📌Note:Thick cases may prevent full insertion)
  • 【Compact & Travel-Friendly】Designed for convenience, the slim and lightweight card reader for camera memory card fits perfectly in your camera bag or laptop sleeve. Protective covers at both ends shield the ports from dust and liquid, while the attached cord keeps everything secure and easily accessible. A reliable companion for on-the-go professionals and creatives(📌Note: "SD"card and "Micro SD" card not included.)
  • 【Plug-and-Play】The SD Card Reader for PC does not require driver or software installation, just connect to your device and start transferring files instantly. Compatible with Windows 11/10/8/7, macOS, and most Android devices. Crafted from heat-resistant aluminum materials, this SD Card Reader for PC delivers reliable performance and enhanced durability, even during long working(📌Note: SD Slot does not support CF express Type A/B/C Cards; SIM, XQD, MS Cards and Memory Stick)
  • 【Wide Device Compatibility】The USB C SD Card Reader works seamlessly with PCs, computers, laptops, cameras, smartphones and tablets featuring USB-C or USB-A ports, including MacBook Air/Pro, XPS, iPhone 15/16, iPad Pro, Samsung Galaxy S23, Microsoft Surface, Acer Aspire, and Predator series. Perfect for quickly accessing files directly on your device without additional apps or internet connections(📌Note:Not compatible with “Lightning” port devices)

Do not revoke the URL immediately in an image load handler if the image remains available. MDN notes that early revocation can break interactions such as opening the image in a new tab or saving it. Revoke it when replacing the file, clearing the component, or unmounting the page instead. Each call to createObjectURL() creates a new URL, even for the same object; the blob URL reference explains the memory implications.

What happens when the user selects a file

  1. The picker returns a FileList through input.files.
  2. Your handler rejects an empty selection or a type your interface does not support.
  3. The browser creates a temporary URL pointing at the local file; it does not upload the bytes.
  4. The image element decodes and displays that local resource.
  5. When the preview is no longer needed, URL.revokeObjectURL() releases the URL reference.

The URL is only useful in the browser context that created it. It is not a permanent URL to send to your API. When the user submits the form, send the original File in FormData (or use your chosen upload protocol).

Validation that helps users without pretending to be security

Use accept as a picker hint

accept="image/*" asks the file picker to emphasize image formats. Users can still select unexpected content in some environments, so keep the JavaScript check. The MDN file-input documentation describes accept as a user-interface filter rather than proof of file contents.

Check type, size, and dimensions when appropriate

A MIME-type check such as file.type.startsWith("image/") gives immediate feedback, but a MIME string alone does not prove that the bytes are a valid image. Enforce authoritative type, size, and content checks on the server before storing or processing the upload. You can check a client-side size limit to avoid an unpleasant preview attempt:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const MAX_BYTES = 10 * 1024 * 1024;
if (file.size > MAX_BYTES) {
  error.textContent = "Choose an image no larger than 10 MB.";
  error.hidden = false;
  return;
}

To inspect dimensions after loading, listen for preview.onload and read preview.naturalWidth and preview.naturalHeight. Treat those values as UI guidance, not a replacement for server-side validation.

Rank #2
SmartQ C368 USB 3.0 Card Reader - Plug & Play, Compatible with Apple & Windows, Supports SD, Micro SD, MS, CF Cards
  • SmartQ C368 USB 3.0 Card Reader: Four-in-one design, supports Micro SD/SD/MS/CF cards, and reads data independently; ideal for plug and play mobile use during travel.
  • High data transfer speed: Supports data transfer speed up to 5GB per second (at USB 3.0 speed), compatible with USB 3.0 and USB 2.0 multi-card readers for CF and MicroSD cards.
  • Multi-system compatibility: Compatible with Windows/Mac OS/Linux and other systems, no driver needed, enjoy a plug and play experience.
  • Working status: Blue LED light indicator, the indicator LED lights up when powered on, the device status is clearly visible.
  • In the Box: SmartQ C368 USB 3.0 Card Reader (memory card not included), Cable organizer, User manual.

Supporting multiple images

Add multiple, create one object URL per accepted file, and keep the URLs in an array so every one can be revoked. The following example also reports rejected files.

<label for="images">Choose images</label>
<input id="images" type="file" accept="image/*" multiple>
<p id="multi-error" role="alert" hidden></p>
<div id="gallery" aria-live="polite"></div>

<script>
const filesInput = document.querySelector("#images");
const gallery = document.querySelector("#gallery");
const multiError = document.querySelector("#multi-error");
let galleryUrls = [];

function clearGallery() {
  galleryUrls.forEach(url => URL.revokeObjectURL(url));
  galleryUrls = [];
  gallery.replaceChildren();
}

filesInput.addEventListener("change", () => {
  clearGallery();
  multiError.hidden = true;
  multiError.textContent = "";

  const rejected = [];
  for (const file of filesInput.files ?? []) {
    if (!file.type.startsWith("image/")) {
      rejected.push(file.name);
      continue;
    }
    const url = URL.createObjectURL(file);
    galleryUrls.push(url);
    const figure = document.createElement("figure");
    const image = document.createElement("img");
    image.src = url;
    image.alt = file.name;
    image.loading = "lazy";
    const caption = document.createElement("figcaption");
    caption.textContent = file.name;
    figure.append(image, caption);
    gallery.append(figure);
  }

  if (rejected.length) {
    multiError.textContent = `Skipped non-image files: ${rejected.join(", ")}`;
    multiError.hidden = false;
  }
});

// Call clearGallery() when this component is destroyed or reset.
</script>

Track URLs independently from DOM nodes. Removing an <img> element does not itself communicate that the blob URL is no longer needed. MDN’s file-input examples show the same thumbnail-and-cleanup approach.

Drag-and-drop uses the same preview function

A drop event exposes files through event.dataTransfer.files. Reuse the rendering logic rather than maintaining a separate image-decoding path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const dropZone = document.querySelector("#drop-zone");

dropZone.addEventListener("dragover", event => {
  event.preventDefault();
  dropZone.classList.add("is-over");
});

dropZone.addEventListener("dragleave", () => {
  dropZone.classList.remove("is-over");
});

dropZone.addEventListener("drop", event => {
  event.preventDefault();
  dropZone.classList.remove("is-over");
  const droppedFiles = [...event.dataTransfer.files]
    .filter(file => file.type.startsWith("image/"));
  // Pass droppedFiles to the same function used by the input handler.
  renderImages(droppedFiles);
});

Make the drop area keyboard-accessible by keeping a real file input inside it or next to it; drag-and-drop should enhance, not replace, the labeled picker. MDN’s file API guide includes drag-and-drop thumbnail handling and URL cleanup.

Object URLs versus FileReader

For a straightforward preview, object URLs are the direct pattern because the URL references the file rather than embedding its bytes into a string. FileReader.readAsDataURL() creates a data URL, which can be convenient when you explicitly need serialized text, but it increases the representation size and has data-URL size limitations. Object URLs still require explicit lifecycle cleanup.

Rank #3
USB3.0 Micro SD Card Reader, 5Gbps 2-in-1 SD Card Reader to USB Adapter, Wansurs Memory Card Reader for SDXC, SDHC, MMC, RS-MMC, Micro SDXC, Micro SD, Micro SDHC and UHS-I Cards (1Pack Black)
  • 【Dual Slots Design】 - This usb sd card reader has Micro SD Card Slot and SD Card Slot with USB 3.0 plug, It could easily transfer the file you need between different devices or review the photos/videos quick.
  • 【5Gbps Speed】 - Extremely fast transfer speed allows you to transfer more files in less time, reducing waiting time, suitable for photographers, studios, and those who need to transfer large files
  • 【Wide Compatibility】 - Memory card reader compatible with Windows system , Mac OS system , Linux and Android. Support SD, MMC, SDHC, DV, Micro SD, T-Flash card.
  • 【Plug and Play】 - Memory card reader for computer and laptop, which can be transmitted through the SD card reader without driver. What’s more, card reader not only relieve the pressure of mobile memory , but also share photos and videos with family and friends anytime and anywhere.
  • 【Compact and Portable】 - This USB card reader body is lightweight , strong heat dissipation and cost-effective. Multifunction card reader for any devices with USB port.
Approach Image source Cleanup Best fit
URL.createObjectURL(file) Temporary blob URL referencing the local file URL.revokeObjectURL(url) Normal previews and thumbnail galleries
FileReader.readAsDataURL(file) Data URL containing an encoded representation Discard the resulting string Cases that specifically require inline serialized data

Whichever method you use, never treat a client-generated preview as evidence that an upload is safe. Validate and process the original upload on the server.

Accessibility and user experience details

  • Use a visible <label> or an accessible name for every file input.
  • Give the preview meaningful alternative text, commonly the selected filename; if the image is decorative, use an empty alt value.
  • Expose rejection messages in an element with role="alert" and avoid silently ignoring files.
  • Keep the preview hidden until a valid image exists, and clear the old image when a new selection is rejected.
  • For galleries, announce changes with aria-live="polite" and provide a clear/reset control.
  • Do not rely on color alone to show drag-over state.

Performance, privacy, and reliability considerations

Object URLs avoid an upload request and let the browser decode the local file. Large images can still consume memory while decoded, so cap client-side file size where a limit improves the experience and avoid creating previews for files you already know you will reject. For many files, revoke the complete URL list before rendering a replacement selection.

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

The selected bytes stay local until your code submits them. Do not log file contents or expose object URLs to unrelated page code. If you draw an image to a canvas, account for cross-origin rules and preserve the original file separately for upload.

Handle an image decode failure with an error listener so a damaged or unsupported file produces feedback:

preview.addEventListener("error", () => {
  if (previewUrl) URL.revokeObjectURL(previewUrl);
  previewUrl = undefined;
  preview.removeAttribute("src");
  preview.hidden = true;
  error.textContent = "The selected file could not be displayed as an image.";
  error.hidden = false;
});

Keep the URL alive while the user may right-click, open, save, zoom, or otherwise interact with the preview. Revoke it when the component is removed; frameworks can call the cleanup from their unmount effect.

Rank #4
Sale
uni SD Card Reader,High Speed USB C to Micro SD Memory Card Adapter USB 3.0
  • 【USB 3.0 + USB C】 Both interfaces support high-speed data transfer up to 5 Gbps, allowing you easily transfer 1G files in seconds. Dual Card Slots, support SDXC, SDHC, SD, MMC, RS-MMC, Micro SDXC, Micro SD and Micro SDHC cards from Camera/ Gopro/ Dash Cam/ Surveillance camera. Backwards compatible with USB 2.0 and USB 1.1. (📌Note: "SD"card and "Micro SD" card not included.)
  • 【Double duty】 Simultaneously reading and writing on two cards to save the constant plugging and pulling of plugs. Enjoy fast photo downloads, smooth video editing and fast 3D Printer file transfers. Double your productivity with simultaneous microSD/SD card access. View recordings of your security cameras, wildlife monitors, private surveillance cameras and car monitors instead of bringing them home to you.(📌Note:only reads and transfers data from the SD and TF card, not directly connect to the camera)
  • 【Plug and Play】uni Card Reader for camera memory card has handy covers at both ends to keep out liquid and dust. Its slim profile makes it easy to store in your camera bag or backpack, and the useful cord keeps it from getting lost and provides convenient access to micro/SD cards when needed. No driver is required in Windows 11/10/8/7/Vista or Mac OS X 10.2 and later. No additional power supply is required. (📌Note:Not compatible with “Lightning” port devices)
  • 【Wide Compatibility】Compatible with iPhone 15 Pro/Pro Max, MacBook Pro (2023~2016), MacBook (2022~2015), iMac Pro (iMac), Acer Aspire Switch 12S/R13, Predator 15/17X, XPS 13/15/17, Alienware 13/15/17, Spectre x360, Microsoft Surface Pro, Book 2, Razer Blade 15/Stealth 13/Pro 17, Samsung Galaxy Tab Pro, S23/ S22 Ultra/ S21/ S20 and most other USB-C / A devices. (📌Note: SD Slot does not support CF express Type A/B/C Cards; SIM, XQD, MS Cards and Memory Stick)
  • 【No Camera Software Required】uni high speed Memory Card Reader connects directly to your Android phone's USB-C port, allowing you to instantly view your footage and manage photo videos without the need for additional apps or Wi-Fi connections. Share your experiences in real-time and never miss an exciting moment again! uni Micro SD USB Adapter with 24/7 customer service and effortless 18-month 𝗐𝖺𝗋𝗋𝖺𝗇𝗍𝗒. Please rest assured we stand behind our products and customers.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common problems and fixes

The image stays hidden

Confirm that the handler assigns preview.src and sets preview.hidden = false. Check the browser console for a selector typo and ensure the script runs after the elements exist.

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

The preview disappears after loading

Look for URL.revokeObjectURL() in an immediate load callback. Move revocation to replacement, reset, or component teardown.

Nothing happens when the same file is selected again

After clearing the preview, set input.value = "". That resets the control so selecting the same path can generate another change event.

Some files are rejected

Inspect file.type and your size rule. Extensions are not reliable proof of content; retain server validation and explain the accepted formats in the UI.

Memory grows after repeated selections

Store every URL returned by createObjectURL() and revoke all old URLs before rendering a new set. Removing image elements alone is insufficient; see MDN’s revokeObjectURL() reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Memory Card Reader, BENFEI 4in1 USB 3.0 and USB-C to SD Micro SD MS CF Card Reader Adapter, 4 Cards Simultaneously Read and Write, Compatible with iPhone 15 Series, MacBook Pro/Air 2023, and More
  • INTEGRATED DESIGN - The integrated-designed BENFEI USB-C/USB 3.0 card reader provide high data speed access to four different card types, the SD(Secure Digital), Micro SD(TF), MS(Memory Stick) and CF(Compact Flash). And with 2in1 USB-C/USB 3.0 design, BENFEI card reader could works with computer or laptop by USB 3.0/2.0 slot or the latest USB Type-C(Thunderbolt 3) slot. A universal card reader solution.
  • INCREDIBLE PERFORMANCE - With latest USB Type-C or the USB 3.0 port, fully enjoy the transfer rates in UHS-I mode up to 160MB/sec, backward Compatible with USB 2.0/1.1. Browse and view photos instantly on your USB-C/USB3.0 smartphones/laptops. (NOTE: The final data speed is decided by the card and USB slot Type )
  • SUPERIOR STABILITY - Built-in advanced IC chip handle the USB-C/USB high speed data transfer signal, allow HD movies trasfer in just seconds. ✅ It is a simultaneously card reader and can read 4 card at the same moment
  • BROAD COMPATIBILITY - Compatible with MacBook Pro 2019/2018/2017/2016, MacBook 2017/2016/2015, iPad Pro 2018, Surface Book 2, Samsung Galaxy S10/S9/S8/Note 8/Note 9, HTC U11/U12, Pixelbook, Dell XPS 15 / XPS 13, Galaxy Book, and many other USB-C Devices. NOTE: SDXC cards (capacity at 64GB or larger) use a special file format "exFAT", which is not supported in Windows XP, Windows Vista before SP1, and Mac OS X before 10.6.6). ❗ Incompatible with Memory Stick (Standard),Memory Stick Micro (M2) and CF Type I
  • 18 MONTH WARRANTY - Exclusive BENFEI Unconditional 18-month Warranty ensures long-time satisfaction of your purchase; Friendly and easy-to-reach customer service to solve your problems timely.

Or skip the browser setup

If your goal is to capture a page image rather than preview a file selected by a visitor, ScreenshotNeo provides a website screenshot API and MCP server. One request returns PNG, JPEG, WebP, or PDF, while its capture steps can accept consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Failed loads, blank pages, bot checks, CAPTCHAs, timeouts, and cache hits are not billed; response headers identify the page verdict and billing result. AI agents can use its MCP tools take_screenshot, get_page_info, and capture_pdf.

Using the API requires an access key. See the ScreenshotNeo documentation for parameters and options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets and custom viewports, retina scale, PDF paper settings and page ranges, HTML/CSS rendering, custom JavaScript and CSS, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration.

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing provides two months free. Create a free ScreenshotNeo account to try it without a card.

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

FAQ

Does previewing upload the file?

No. Creating an object URL only gives the current page a local reference. Upload occurs later when your code sends the original File.

Can I preview videos or PDFs this way?

The pattern is shown for images. Other media need an element and validation appropriate to that format.

Should I revoke a URL after the image loads?

Not if the preview remains interactive. Revoke it when replacing, clearing, or destroying the preview component.

Is accept="image/*" secure validation?

No. It guides selection. Validate file content and policy on the server before storing or processing the upload.

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

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.