Sometimes, we want to show an image preview before upload with JavaScript.
In this article, we’ll look at how to show an image preview before upload with JavaScript.
How to show an image preview before upload with JavaScript?
To show an image preview before upload with JavaScript, we use the FileReader
constructor.
For instance, we write
<input type="file" onchange="onFileSelected(event)" />
<img id="myimage" height="200" />
to add the input and img elements.
Then we write
function onFileSelected(event) {
const [selectedFile] = event.target.files;
const reader = new FileReader();
const imgtag = document.getElementById("myimage");
imgtag.title = selectedFile.name;
reader.onload = (event) => {
imgtag.src = event.target.result;
};
reader.readAsDataURL(selectedFile);
}
to set the onchange
attribute to onFileSelected(event)
to use the onFileSelected
function as the input’s change event listener.
In it, we get the file from event.target.files
.
Then create a FileReader
object.
Next, we select the img element with getElementById
.
Then we set the reader.onload
property to a function that runs when readAsDataURL
is done.
In it, we get the read image base64 URL string from event.target.result
and set the img element’s src attribute to the base64 URL string.
Finally, we call readAsDataURL
to read the file into a base64 URL.
Conclusion
To show an image preview before upload with JavaScript, we use the FileReader
constructor.