Preview an image before it is uploaded
To preview an image before upload, use FileReader and bind an event listener to the file input. The file will be read as a data URL and set it as the src
attribute for an image tag:
For the corresponding HTML:
This rapidly shows user-selected image as a preview without uploading it to the server.
Optimizing previews with Blob URLs
Generating blob URLs can be faster and less memory-intensive than using FileReader, especially for larger files. Use the URL.createObjectURL()
method to create a blob URL:
Memory resource management
It's important to clean up resources after use to prevent memory leaks. Revoke the blob URL after the image is no longer needed:
Handling multiple images
For multiple image previews, iterate over the files
array and create previews for each image:
Prepare your HTML for multiple previews:
Solutions for older browsers
IE does not support FileReader
and URL.createObjectURL
, but you can use proprietary CSS filter
properties with IE-specific script wrapped in HTML conditional comments when required.
Consider performance and user experience
Your users and servers will thank you for showing the selected image preview before sending uploads to the server, saving bandwidth and resources.
In addition, use CSS to ensure that your large image previews don't escape their bounding box:
Lastly, use semantic HTML for a better UX with your image input and previews. A solid interface is always a win!
Was this article helpful?