In this article we’ll see how to create an image upload preview in JavaScript by leveraging the features of the FileReader
class.
We essentially need to read the chosen image as a data URL (Base64). The FileReader
class provides the readAsDataURL()
method, which we can use like this:
function fileToDataURI(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject;
reader.readAsDataURL(file);
});
}
This function uses Promises to return the resulting data URL from reading the File
object. We can then handle the change
event on the input field as follows:
function handleFile(input, preview, thumb, caption) {
input.addEventListener('change', async (e) => {
preview.classList.remove('visible');
const file = e.target.files && e.target.files.length > 0 ? e.target.files[0] : null;
if(!file) {
return;
}
const src = await fileToDataURI(file);
const fileName = file.name;
thumb.setAttribute('src', src);
caption.innerText = fileName;
preview.classList.add('visible');
});
}
We obtain the data URL and the image name from the File
object contained in the input field’s files
array. With this data we can populate the DOM elements that make up our preview.
Demo
JavaScript Image Upload Preview
Conclusion
The FileReader
class allows us to get the data URL of the selected image for upload, enabling us to display its preview on the page.