Computer >> Computer tutorials >  >> Programming >> Javascript

How to preview an image before and after upload in HTML and JavaScript?


To preview an image before and after upload, you need to try the following code − HTML

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id = "form1" runat = "server">
   <input type ='file' id = "demo" />
   <img id = "myid" src = "#" alt = "new image" />
</form>

The following is the jQuery −

function display(input) {
   if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(event) {
         $('#myid').attr('src', event.target.result);
      }
      reader.readAsDataURL(input.files[0]);
   }
}

$("#demo").change(function() {
   display(this);
});