How to preview image before upload using JavaScript ?

1 min read

In this tutorial, we will be learning to preview an image without actually uploading it to the server. We will use couple of lines of JavaScript code to achieve this.

We will have an “input” HTML element to trigger the file selection box along with an “img” element that is used to show the preview of the image selected.

Follow this video for complete guidance :

Full Source Code :

<style>
      img.image-preview[src='']{
        display: none;
      }


    </style>

<img class="image-preview">

<div>
  <input type="file" class="upload-photo" width="300">
</div>


<script type="text/javascript">
  document.getElementsByClassName('upload-photo')[0].onchange = function () {
    var src = URL.createObjectURL(this.files[0]);
    document.getElementsByClassName('image-preview')[0].src = src;
  }

  document.getElementsByClassName('image-preview')[0].onclick = function() {
    document.getElementsByClassName('upload-photo')[0].click();
  }
</script>

 

Recommended For You

About the Author: Admin