Hendrik Lammers

Use FileReader to preview an image

The FileReader object makes it possible to read the contents of a file from the local file system. These files have to be selected by either a file input <input type="file" /> or by drag and drop.
There are various methods available on the FileReader object to read the contents of the file. readAsDataURL() can be used to get a data URL from an image file, which than can be used as src for an Image to show it on the screen.

const input = document.getElementById('file-input')
const preview = document.getElementById('preview')

input.addEventListener('change', (event) => {
  const files = event.target.files
  if (files.length && files[0].type.startsWith('image/')) {
    const reader = new FileReader()

    reader.onload = (event) => {
      const image = new Image()
      // The result contains a data URL of the image
      image.src = event.target.result


See MDN for more details on the FileReader object