How to render a file image preview in JavaScript

Written by
Published on
Modified on
Category

A pretty cool feature that you can add to your file upload elements, if you are working with images, is the ability to render a preview on the fly so that the user has some form of queue as to what is about to be uploaded.

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.

<input type='file' id='file1' />
<div><img id='imgPreview'/></div>

Also note that we created an <img> placeholder element that will be used to render the image preview.

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('file1').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('imgPreview');
  const file = document.querySelector('#file1').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:

Preview

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.

Comments

No messages posted yet

Developer Poll

Q:

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post