Rendering a file image preview in JavaScript is a common requirement in most modern web applications these days. Whether you're building a file uploader or simply want to give users a sneak peek of their selected images, this feature greatly improves the user experience. In this guide, we'll walk you through the process of creating an image preview using vanilla JavaScript, ensuring your users can see their selected files before uploading.
And thanks to the FileReader object we can do just that by taking the File objects from any <input> element and then calling the readAsDataUrl() method of the reader in order to retrieve the base 64 encoding of the image being uploaded.
So let's walk through that process, starting with the most obvious step of creating a file upload element.
Step 1: Set up your HTML structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Preview Example</title>
</head>
<body>
<input type="file" id="fileInput">
<br>
<img id="imagePreview" src="" alt="Image Preview" style="max-width: 300px; display: none;">
</body>
</html>
Also note that we created an <img> placeholder element that will be used to render the image preview.
Step 2: Add event listener to input
We can add an onchange event listener to the input element in order to trigger the FileReader creation when a user has uploaded any file.
<script>
window.addEventListener('load', function(){
document.getElementById('fileInput').addEventListener('change', function(e){
filePreview();
});
});
</script>
The following helper function will be used to create the FileReader in order to retrieve the image data to render.
function filePreview(){
const preview = document.getElementById('imagePreview');
const file = document.querySelector('#fileInput').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
// result is a base64 string
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
Here is a quick demo of the functionality:
How it works
HTML5 introduced the File API which gave the browser access to a users local file system, but only on files that are explicitly selected by a user, mainly through the file upload control.
You can retrieve any files selected by a user in an <input> element through the files property. The files property is essentially an instance of FileList, which itself is a collection of File objects.
const selectedFile = document.getElementById('file1').files;
Let's take a look under the hood and see what the FileList object consists of.
In this case, it's mainly just a single File object with the given files name, size and type.
When you actually create an instance of FileReader however and pass a given File object, you can retrieve the base64 encoded data for the file, which looks like the following.
Again, this makes for a good visual queue when users are uploading image files, particularly if you don't have AJAX file upload functionality.
You can see a full running demo over on Codepen.io.
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on:
Have a question on this article?
You can leave me a question on this particular article (or any other really).
Ask a question