Javascript Preview Image Before Upload

Advertisement

When users are uploading images, they are not sure if they are uploading the right image. You can help them by adding image preview before upload. Fortunately, you can do this with just HTML and Javascript.

image preview before upload

Image Upload Button

First, we create the html button that allows us to upload a picture.

<div class="container" id="upload">
  <form>
    <input type="file" accept="image/*" name="image" value="fileupload" id="file" onchange="loadFile(event)">
  </form>
</div>

We have added an event that will be fired once the user chooses a file: onchange.

We have created an input that only accepts images. once the image is selected, the event onchange is fired and function loadFile is called.

Image Preview Container

To preview the image we need to create an image tag. This will be the container used to display the image.

<strong>Add the image tag with an id below the form tag.</strong>

<div class="container" id="upload">
 <form>
    <input type="file" accept="image/*" name="image" value="fileupload" id="file" onchange="loadFile(event)">
  </form>
  <img id="output" width="300" />
</div>

Loading Image Using Javascript

Now on to javascript. Lets add the code that will display the image once the onchange event is fired.

<script>
  function loadFile(event) {
    var image = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
   };
</script>

To recap the whole tutorial, here is how all the code will look like.

<body>
  <div class="container" id="upload">
    <form>
      <input type="file" accept="image/*" name="image" value="fileupload" id="file" onchange="loadFile(event)">
    </form>
    <img id="output" width="300" />
  </div>
  <script>
    function loadFile(event) {
      var image = document.getElementById('output');
      image.src = URL.createObjectURL(event.target.files[0]);
    };
  </script>
 </body>

You can play around with the code on codepen:

See the Pen image-preview-upload by Avic (@Axeaxel) on CodePen.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.