Preview Image Before Upload Using JavaScript
Last Updated : Jul 1, 2023
IN - JavaScript HTML CSS | Written & Updated By - Dikshita
In this tutorial we will show you how to preview image before upload using JavaScript,HTML and CSS, Image preview is a great feature for user to check there image before upload whether the correct image is going to upload or if the image looks nice or not etc.
You may also like upload multiple images with preview using jQuery and PHP.
CHECK OUT THIS TUTORIAL LIVE DEMO →
To Preview Image Before Upload It Takes Only One Step:-
- Make a HTML file and define markup,scripting and styling
Step 1. Make a HTML file and define markup,scripting and styling
We make a HTML file and save it with a name preview.html
<html> <head> <script type='text/javascript'> function preview_image(event) { var reader = new FileReader(); reader.onload = function() { var output = document.getElementById('output_image'); output.src = reader.result; } reader.readAsDataURL(event.target.files[0]); } </script> <style> body { width:100%; margin:0 auto; padding:0px; font-family:helvetica; background-color:#0B3861; } #wrapper { text-align:center; margin:0 auto; padding:0px; width:995px; } #output_image { max-width:300px; } </style> </head> <body> <div id="wrapper"> <input type="file" accept="image/*" onchange="preview_image(event)"> <img id="output_image"/> </div> </body> </html>
In this step we create a file tag that accepts only images and it calls preview_image() function
with the change event as a parameter when user choose image from folder.
In preview() function we first create FileReader object to get the file data and then when the reader is loaded we create a function to get the output image and change its source to result and then we use readAsDataURL to preview the image.
You may also like jQuery live preview.
Thats all, this is how to preview image before upload using JavaScript, CSS and HTML. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.
I hope this tutorial on preview image before upload JavaScript helps you and the steps and method mentioned above are easy to follow and implement.