Html - Display image after selecting filename
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:
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:
And the corresponding HTML:
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:
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 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:
Relay issues to the user, whether it's a corrupted file or read permission blips.
Was this article helpful?