\n\n\nUpon selection of a file, previewImage is activated, interpreting the image and setting #preview's src to display it. No additional buttons or event listeners needed here.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Anton Shumikhin","url":"https://explain.codes//author/anton-shumikhin"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-12-27T14:15:01.430Z","dateModified":"2024-12-27T14:15:02.835Z"}
Explain Codes LogoExplain Codes Logo

Show an image preview before upload

javascript
responsive-design
best-practices
file-reader-api
Anton ShumikhinbyAnton Shumikhin·Dec 27, 2024
TLDR

Instantly preview images using JavaScript. Connect it to <input type="file"> and employ FileReader to display the loaded image within an <img> element. The snippet below illustrates using a HTML5 FileReader API:

<input type="file" oninput="previewImage(this.files[0])" accept="image/*"> <img id="preview" style="max-width: 200px;"> <script> function previewImage(file) { const reader = new FileReader(); reader.onload = () => document.getElementById('preview').src = reader.result; reader.readAsDataURL(file); // Don't try this with a rubber duck — unless it's a JPEG one 🦆 } </script>

Upon selection of a file, previewImage is activated, interpreting the image and setting #preview's src to display it. No additional buttons or event listeners needed here.

How about multiple previews?

Handling several images at once? Try the multiple attribute in your <input> tag to enable multi-image selection. The JavaScript part captures all the selected files and maps them into snappy thumbnails:

<input type="file" id="image-upload" accept="image/*" multiple> <div id="gallery"></div> <script> function updateImageDisplay() { const curFiles = document.getElementById('image-upload').files; const gallery = document.getElementById('gallery'); gallery.innerHTML = ''; // let the gallery breathing, clear out any previous thumbnails for(const file of curFiles) { const imageObjectUrl = URL.createObjectURL(file); const imgElement = document.createElement('img'); imgElement.style.maxWidth = '150px'; imgElement.src = imageObjectUrl; // because images deserve their URL, too gallery.appendChild(imgElement); // this gallery grows with every cute image you give it 🖼️ } } document.getElementById('image-upload').addEventListener('change', updateImageDisplay); </script>

This freshens up the previews each time a new file(s) is selected. Opting for URL.createObjectURL() gives you a much faster visualization without the need to read the entire file - that's an efficiency boost for the browser!

More than just a quick look: Best practices

Delving in multiple files or larger applications asks for better code structure and security precautions.

Working efficiently with Object URLs

URL.createObjectURL() creates a reference pointer to the file rather than a heavy, base64-encoded data URL - a lighter carry for larger or multiple images. Be courteous to your memory and avoid potential leaks: release object URLs post-use with URL.revokeObjectURL().

Security concerns in action

File type validation is a must on both client and server sides. Use the accept attribute to restrict user file types, and double-check the type of file objects within JavaScript. Client-side validation alone won't cut it for tight security.

Style and responsiveness

Better visuals with thumbnails mean ensuring responsiveness:

#gallery img { max-width: 100%; height: auto; padding: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }

Looking at alternatives

FileReader API can also double up for image previews. It reads file data, converting it into a Data URL. When you need more control over how file data is handled before it shapes up into an image, consider this mechanism.

HTML5 compliance and user accessibility

Align your markup with HTML5 standards to ensure smooth cross-browser functionality and assistive technology compliance. Label your input elements aptly for accessibility:

<label for="image-upload">Upload images:</label> <input type="file" id="image-upload" accept="image/*" multiple>

Enhancing user experience: Drag and drop

Add a splash of fun! Integrate drag-and-drop functionality: the drop area grabs the images, JavaScript takes over to read files and preview images, much akin to the traditional file input action.