Skip to main content

Preview a Selected Image with JavaScript

· One min read
Apache Wangye
Software developer and technical writer

A browser can preview a file explicitly selected by the user without uploading it first. Validate the MIME type, size, and number of files before rendering the preview.

<input id="imageInput" type="file" accept="image/*">
<img id="preview" alt="Selected image preview" width="200" height="200">

<script>
const input = document.getElementById("imageInput");
const preview = document.getElementById("preview");
let currentUrl;

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

if (!file.type.startsWith("image/")) {
input.value = "";
throw new Error("Please select an image file");
}

if (currentUrl) URL.revokeObjectURL(currentUrl);
currentUrl = URL.createObjectURL(file);
preview.src = currentUrl;
});

window.addEventListener("beforeunload", () => {
if (currentUrl) URL.revokeObjectURL(currentUrl);
});
</script>

URL.createObjectURL avoids converting the complete file to Base64, making it efficient for previews. Revoke old URLs when they are replaced or no longer needed.

Client-side validation improves usability but does not make an upload safe. The server must independently validate file size, content, extension, storage path, and authorization.

Page views: --

Total views -- · Visitors --