Explain Codes LogoExplain Codes Logo

Loading an image to an from an

javascript
file-reader
async-await
error-handling
Nikita BarsukovbyNikita Barsukov·Nov 10, 2024
TLDR

Display a selected image in an <img> with JavaScript and the FileReader API. Attach an onchange event to the <input type="file">, read the selected file, and set the src of the <img> to the file's data URL.

document.querySelector('input[type="file"]').onchange = event => { let reader = new FileReader(); reader.onload = e => document.querySelector('img').src = e.target.result; reader.readAsDataURL(event.target.files[0]); };
<input type="file" /> <img />

Ensure the <input> and <img> tags have correct identifiers.

Next-level browser support

Aforementioned example is straightforward, but compatibility with broad array of browsers is critical. Check FileReader support and provide a fallback:

if (window.FileReader) { /* Great! Let's load some images 🚀 */ } else { /* Fallback routine, activate! 💁‍♂️ */ }

For those browsers with flashbacks of their ancestors that don't support FileReader, ponder upon another upload strategy such as submitting to a hidden <iframe> to pre-upload the file to the server.

Efficient use of system resources

When exploiting URL.createObjectURL, don't forget to shack off the Object URL with URL.revokeObjectURL to recycle memory when the image isn't needed. It's eco-friendly. Remember, every byte counts! 💾

Premium image loading

When your code demands intimate control over file loading, employ async/await with FileReader with vigilant error handling and handling around Promises.

Asynchronous file reading: Hands-on

Applying async/await

async function readImageFile(file) { const reader = new FileReader(); return new Promise((resolve, reject) => { reader.onload = event => resolve(event.target.result); /* Resolution, sweet resolution. */ reader.onerror = reject; reader.readAsDataURL(file); }); } document.querySelector('input[type="file"]').onchange = async event => { try { const imageDataUrl = await readImageFile(event.target.files[0]); document.querySelector('img').src = imageDataUrl; /* Hey presto! */ } catch (error) { console.error("Error reading file", error); /* I read... therefore, I am. Or am I? */ } };

UX with styles

Vary the style of the <img> tag to ensure all images look smashing regardless of dimensions. Play with max-width and height for example.

Prepping for uncertain events

Implement error handling for FileReader and image loading process like a pro. It's like packing an umbrella on a cloudy day. ☂️

Dealing with DOM like a Boss.

Building elements from scratch

To test functionality, create <input> and <img> elements using document.createElement.

jQuery: Because, why not?

If minimalist syntax is your style, leverage jQuery to manipulate file input and images.