JQuery Magic: Get a Sneak Peek of Your Image Before Uploading

How to Preview Image before it is Uploaded using JQuery

Preview Image Before Upload - JQuery

In this article we will learn how to preview image before upload using JQuery . We will use some methods provided by JS like change() , readAsDataURL() . So let's see how to use it .

index.html :


<!DOCTYPE html>
<html>
<head>
 <title>Upload and Preview</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

 <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
 
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

 <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

 <div class="row my-5">
  <div class="col-4"></div>
  <div class="col-4 text-center">
   <h2>Upload Image and Preview</h2>
   <input type="file" name="image" id="upload_img" class="form-control">
   <h5>preview</h5>
   <img src="#" id="preview_img" class="img-fluid" style="border-radius: 10px;">
  </div>
  <div class="col-4"></div>
 </div>

 <script src="upload.js"></script>

</body>

upload.js :


$("#upload_img").change(function() {
 console.log(this);
 readURL(this);
});

function readURL(input) {
  if (input.files && input.files[0]) {
   var reader = new FileReader();

   reader.onload = function(e) {
    $('#preview_img').attr('src', e.target.result);
   }

     reader.readAsDataURL(input.files[0]); // convert to base64 string
 }
}

output :


Preview Image Before Upload - JQuery



Thank you for reading this article 😊

For any query do not hesitate to comment 💬




Previous Post Next Post

Contact Form