To preview a selected image before uploading it, handle the file input’s change event, read the first File from input.files, and set an <img> element’s src to URL.createObjectURL(file). Revoke the previous object URL when the user replaces or clears the image. If your application specifically needs the image represented as text, use FileReader.readAsDataURL() instead.
Basic image preview with an object URL
A browser cannot read an arbitrary local pathname supplied by script. The user must choose a file through a file input or provide it through a drag-and-drop operation. The resulting File object can be displayed without uploading it.
<label for="image-file">Choose an image</label>
<input id="image-file" type="file" accept="image/*">
<p id="image-status" role="status" aria-live="polite"></p>
<img id="image-preview" alt="Selected image preview" hidden>
<script>
const input = document.querySelector('#image-file');
const preview = document.querySelector('#image-preview');
const status = document.querySelector('#image-status');
let objectUrl = null;
input.addEventListener('change', () => {
const file = input.files?.[0];
if (!file) {
if (objectUrl) URL.revokeObjectURL(objectUrl);
objectUrl = null;
preview.removeAttribute('src');
preview.hidden = true;
status.textContent = 'No image selected.';
return;
}
if (!file.type.startsWith('image/')) {
if (objectUrl) URL.revokeObjectURL(objectUrl);
objectUrl = null;
preview.removeAttribute('src');
preview.hidden = true;
status.textContent = 'Please choose an image file.';
return;
}
if (objectUrl) URL.revokeObjectURL(objectUrl);
objectUrl = URL.createObjectURL(file);
preview.src = objectUrl;
preview.hidden = false;
status.textContent = `${file.name} selected.`;
});
window.addEventListener('beforeunload', () => {
if (objectUrl) URL.revokeObjectURL(objectUrl);
});
</script>
accept="image/*" guides the file picker, but it is not complete validation. The type check in the example gives immediate feedback; validate uploads again in the service that receives them.
Why URL.createObjectURL() works
URL.createObjectURL(file) creates a temporary URL pointing at the selected File or another Blob. Assigning that URL to img.src lets the browser decode and display the image locally. Each call creates a unique URL, so retain the value and call URL.revokeObjectURL() after the preview is replaced, removed, or otherwise no longer needed. MDN documents this pattern in its file API examples.
#1 Best Overall
- 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
Using FileReader.readAsDataURL()
A data URL embeds the file content in a string. Choose this approach when another part of your application needs that data-URL representation, rather than merely a source for an image element.
<input id="data-file" type="file" accept="image/*">
<img id="data-preview" alt="Selected image preview" hidden>
<p id="data-status" role="status" aria-live="polite"></p>
<script>
const dataInput = document.querySelector('#data-file');
const dataPreview = document.querySelector('#data-preview');
const dataStatus = document.querySelector('#data-status');
dataInput.addEventListener('change', () => {
const file = dataInput.files?.[0];
if (!file) {
dataPreview.hidden = true;
dataStatus.textContent = 'No image selected.';
return;
}
if (!file.type.startsWith('image/')) {
dataPreview.hidden = true;
dataStatus.textContent = 'Please choose an image file.';
return;
}
const reader = new FileReader();
reader.addEventListener('load', () => {
dataPreview.src = reader.result;
dataPreview.hidden = false;
dataStatus.textContent = `${file.name} selected.`;
});
reader.addEventListener('error', () => {
dataPreview.hidden = true;
dataStatus.textContent = 'The image could not be read.';
});
reader.readAsDataURL(file);
});
</script>
readAsDataURL() is asynchronous. Its result is available after the load event and can be assigned to src. See the MDN readAsDataURL reference and the broader FileReader documentation.
Object URL or data URL?
| Approach | Preview source | Cleanup | Use it when |
|---|---|---|---|
URL.createObjectURL(file) |
Temporary URL for a File or Blob |
Call URL.revokeObjectURL() when replaced or removed |
You only need to point an image element at the selected file |
FileReader.readAsDataURL(file) |
Data URL delivered through the reader’s result | No object URL to revoke | You specifically need the file content as a data URL |
The available documentation does not establish a universal performance winner. Select based on the representation your application needs and implement cleanup for dynamic object-URL previews.
Previewing several selected images
Add multiple, iterate through the FileList, and retain each URL so it can be revoked when its card is removed.
<input id="gallery-files" type="file" accept="image/*" multiple>
<div id="gallery"></div>
<p id="gallery-status" role="status" aria-live="polite"></p>
<script>
const galleryInput = document.querySelector('#gallery-files');
const gallery = document.querySelector('#gallery');
const galleryStatus = document.querySelector('#gallery-status');
const urls = new Set();
galleryInput.addEventListener('change', () => {
gallery.replaceChildren();
for (const url of urls) URL.revokeObjectURL(url);
urls.clear();
const files = [...(galleryInput.files || [])];
const images = files.filter(file => file.type.startsWith('image/'));
galleryStatus.textContent = images.length
? `${images.length} image${images.length === 1 ? '' : 's'} selected.`
: 'No supported images selected.';
for (const file of images) {
const url = URL.createObjectURL(file);
urls.add(url);
const figure = document.createElement('figure');
const image = document.createElement('img');
image.src = url;
image.alt = `Preview of ${file.name}`;
const caption = document.createElement('figcaption');
caption.textContent = file.name;
figure.append(image, caption);
gallery.append(figure);
}
});
window.addEventListener('beforeunload', () => {
for (const url of urls) URL.revokeObjectURL(url);
});
</script>
For a production gallery, associate each URL with its preview element and revoke it immediately when that individual preview is deleted. The same routine can process files supplied by drag and drop; MDN describes this shared flow in its file drag-and-drop guide.
Rank #2
- 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
Adding drag and drop without removing the picker
Keep a real, labeled input available for keyboard and assistive-technology users. A drop zone can forward its files to the same preview function:
<label id="drop-zone" for="drop-input">Drop images here or choose files</label>
<input id="drop-input" type="file" accept="image/*" multiple>
<div id="drop-gallery"></div>
<script>
const zone = document.querySelector('#drop-zone');
const dropInput = document.querySelector('#drop-input');
function previewFiles(fileList) {
// Call the same gallery-rendering routine used by the input change handler.
// fileList is a FileList or an array of File objects.
}
dropInput.addEventListener('change', event => previewFiles(event.target.files));
zone.addEventListener('dragover', event => {
event.preventDefault();
zone.dataset.dragging = 'true';
});
zone.addEventListener('dragleave', () => delete zone.dataset.dragging);
zone.addEventListener('drop', event => {
event.preventDefault();
delete zone.dataset.dragging;
previewFiles(event.dataTransfer.files);
});
</script>
In a complete implementation, put the gallery code from the multiple-file example inside previewFiles. Announce unsupported files and empty drops in visible text or a live status region rather than relying only on color or a temporary visual effect.
Accessibility and interface behavior
- Use a visible label or a label-backed control with a meaningful name.
- Give each preview useful alternative text; for a purely decorative duplicate, use an empty
altvalue instead. - Provide a text status for selection errors, unsupported files, and an empty selection.
- Explain how to replace or clear the current preview.
- Do not hide the only file-picker control when adding drag and drop.
These practices make the interaction understandable even when a drop zone, image decoding, or CSS styling is unavailable.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Common problems and fixes
The preview stays blank
Confirm that the handler reads input.files[0], that a file was actually selected, and that preview.src receives the object URL or completed reader result. Check the browser console for errors and ensure the image is not still hidden.
The old image remains after choosing a new one
Revoke the previous URL before assigning the new one, clear the old src when there is no selection, and reset the preview’s visibility.
Rank #3
- 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.
Memory grows after repeated replacements
Object URLs remain usable until revoked or the document is unloaded. Store the current URL, revoke it on replacement and removal, and revoke all URLs in a multi-image collection when the collection is cleared.
accept="image/*" did not prevent a non-image file
accept is a picker hint, not a complete validation mechanism. Inspect the selected file’s type for immediate UI feedback and perform authoritative validation when processing the upload.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteDrag and drop does nothing
Cancel the dragover and drop events with preventDefault(). Without that, the browser may handle the drop as navigation instead of exposing dataTransfer.files. Ensure the drop target is large enough and that the picker remains usable.
The data-URL example has no result yet
FileReader completes asynchronously. Set src inside its load handler, not immediately after calling readAsDataURL().
Or skip the browser setup
If what you need is a screenshot of a public web page rather than a local-upload preview, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be disabled individually. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Use the ScreenshotNeo documentation for authentication and options. A minimal call is:
Rank #4
- 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
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}`);
Every plan includes the feature set: full-page and selector captures, device and retina settings, PDF controls, custom CSS and JavaScript, clicks, waits, blocking rules, headers, cookies, user agents, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Further references
For file-selection behavior, see MDN’s file input reference and File API overview. Browser compatibility and documentation can change, so verify support for any specific browser/version matrix you must guarantee.
Frequently Asked Questions
Can JavaScript read a user’s local file path?
No. The browser exposes a user-selected File through a file input or drop operation, not an arbitrary pathname.
Do I need to upload the image to preview it?
No. An object URL or FileReader data URL can display the selected file locally before any network request.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWhen should I revoke an object URL?
Revoke it when its preview is replaced, removed, or cleared; also revoke retained URLs when a dynamic gallery is destroyed.
Can the same code handle camera captures?
If the browser supplies the capture as a File through the input, the same preview handler can process it.
Quick Recap
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.

