Clue Mediator

How to preview selected image from input type file using jQuery

📅February 20, 2022

In this article, we will show you how to preview selected image from input type file using jQuery. Sometimes we may need to display the image before it is uploaded. So in this example, we will demonstrate it to you.

Checkout more articles on JavaScript

Here we will use the FileReader to read the target result and set it in the image using jQuery. Use the following code to display a preview image.

index.html




  <title>Preview selected image from input type file - Clue Mediator</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>




  <h4>Preview selected image from input type file - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue
      Mediator</a></h4>

  <input type="file" name="file" id="img-upload">
  <img src="" id="img-upload-tag" width="150px">

  <script type="text/javascript">
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
          $('#img-upload-tag').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
      }
    }
    $("#img-upload").change(function () {
      readURL(this);
    });
  </script>

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂