Explain Codes LogoExplain Codes Logo

Html - Display image after selecting filename

html
file-upload
user-experience
error-handling
Nikita BarsukovbyNikita Barsukov·Aug 10, 2024
TLDR

Instantly display a chosen image with HTML and JavaScript, using an <input> for file selection and an <img> for display. Utilize the FileReader to convert the file to a data URL, and update the image's src attribute. Below is the succinct code:

<input type="file" onchange="document.getElementById('output').src = URL.createObjectURL(this.files[0])"> <img id="output">

The onchange event initiates an immediate preview by creating a temporary URL that the <img> can use as src. It's straightforward, fast, and no need to wrestle with FileReader.

Graceful degradation: Supporting older browsers

For those who can't let go of older browsers where URL.createObjectURL is a fairy tale, we have the reliable FileReader. It's a bit more loquacious, but it has your back:

// Here be dragons, or in other words, FileReader...Take care, adventurer! function readURL(input) { // Ensure there's something to read if (input.files && input.files[0]) { var reader = new FileReader(); // Update image once it's read reader.onload = function(e) { $('#imagePreview').attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); // Voila! It's a base64 string! } } // The magical line that starts it all $("#fileInput").change(function() { readURL(this); });

And the corresponding HTML:

<input type="file" id="fileInput"> <img id="imagePreview" src="#" alt="your image" />

Improving user experience with libraries

After mastering the basics, you can level up the user experience. Libraries like jQuery-File-Upload or JavaScript-Load-Image assist in manipulating images, adding resizing or cropping capabilities right in the browser.

Image-only upload

Prevent users from casting the wrong spells (i.e., uploading non-image files). The accept attribute limits selection to image files:

<input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(this)">

Only images can pass this gatekeeper, limiting the chances of unexpected file types crash-landing on your server.

Multiple previews and thumbnails generation

Ever felt powerful after casting a spell? Amplify that feeling by creating a gallery of thumbnails. With HTML5, it's a breeze:

// A bit of magic to bring you a medley of thumbnails! function updateImageDisplay() { var gallery = document.getElementById('gallery'); gallery.innerHTML = ""; var curFiles = input.files; if(curFiles.length === 0) { // No files to display? No problem! Just a friendly message. var para = document.createElement('p'); para.textContent = 'No files currently selected for upload'; gallery.appendChild(para); } else { var list = document.createElement('ol'); gallery.appendChild(list); for(var i = 0; i < curFiles.length; i++) { var listItem = document.createElement('li'); var para = document.createElement('p'); if(validFileType(curFiles[i])) { // Well done, you selected a valid file! para.textContent = 'File name ' + curFiles[i].name + ', file size ' + returnFileSize(curFiles[i].size) + '.'; var image = document.createElement('img'); image.src = window.URL.createObjectURL(curFiles[i]); listItem.appendChild(image); listItem.appendChild(para); } else { // Oops, wrong file! No worries, just update your selection. para.textContent = 'File name ' + curFiles[i].name + ': Not a valid file type. Update your selection.'; listItem.appendChild(para); } list.appendChild(listItem); } } }

A bit of visual feedback as they select files amplifies user interaction, making your UI an enchanting and engaging experience.

Dealing with errors

To brace your app against edge cases, use FileReader's onerror event:

reader.onerror = function(event) { // Alerting that an error occurred, because transparency is cool! console.error("File could not be read! Code " + event.target.error.code); };

Relay issues to the user, whether it's a corrupted file or read permission blips.