Step by step guide to creating preview image
We’ll start off with a simple HTML page with a form and and input element which accepts only image files. Notice that we have an
img element with empty
src attribute, which we’ll use to display selected image.
Firstly, we’ll update the preview after user picks image. We will do that by handling
onchange event which is triggered once user selects the image. In order to do that we create a new
<script> section with an empty function. Later on we’ll implement it to create preview. Notice that we’re passing element as a parameter, which in this case should be our
Then we hook it up with
onchange event. Note that we’re passing input element as a parameter using
The next step it so retrieve selected file using the
files array which can be accessed from the element. To make it simple I’ve assumed that there is only one file.
To read the file we’ll use
<a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL">FileReader.readAsDataURL</a>, which will convert image into data url.
Then we will use the result (base64 encoded data url image) as an preview image. In this case we have to wait until
readAsDataURL is done to get the result, which happens inside load event listener.
This will display the image, in full size, so you may want to consider styling it and constraining width and height :)