How to Show a Preview of an Image Before Uploading it Using jQuery & JavaScript?

In popular networking sites such as Facebook and Linkedin, you might have observed the feature called Image Preview. Say for instance when you upload a new image as your profile picture, this option lets you preview it and only when you click Save, the new image gets uploaded. This blog shows you how to enable a thumbnail preview of an image using jQuery and JavaScript immediately after selecting the file to be uploaded. 

Read: How to Reduce the Image size using PHP Code/a>



CSS used for thumbnail preview div:

 
#imagePreview {
width: 180px;
height: 180px;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}

Example with HTML&Jquery:

<div id="PreviewPicture"></div>
<input id="FileUpload" type="file" name="ImageUpload" class="image" />
 $(function() {
  $("#FileUpload").on("change", function(){
   var files = !!this.files ? this.files : [];
   if (!files.length || !window.FileReader) return; // Check if File is selected, or no FileReader support
   if (/^image/.test( files[0].type)){ //  Allow only image upload
    var ReaderObj = new FileReader(); // Create instance of the FileReader
    ReaderObj.readAsDataURL(files[0]); // read the file uploaded
    ReaderObj.onloadend = function(){ // set uploaded image data as background of div
    $("#PreviewPicture").css("background-image", "url("+this.result+")");
   }
  }else{
    alert("Upload an image");
  }
 });
});

Example with HTML&Javascript:

<div id="PreviewPicture"></div>
<input id="FileUpload" type="file" name="ImageUpload" class="image" onchange="ImagePreview()" /> />
function ImagePreview() { 
 var PreviewIMG = document.getElementById('PreviewPicture'); 
 var UploadFile    =  document.getElementById('FileUpload').files[0]; 
 var ReaderObj  =  new FileReader(); 
 ReaderObj.onloadend = function () { 
    PreviewIMG.style.backgroundImage  = "url("+ ReaderObj.result+")";
  } 
 if (UploadFile) { 
    ReaderObj.readAsDataURL(UploadFile);
  } else { 
     PreviewIMG.style.backgroundImage  = "";
  } 
}

Note: The readAsDataURL method is used to read the contents of the specified Blob or File. When the file or Blob read operation is completed the readyState is done and loadend is triggered. When the loadend is triggered the result attribute contains the file’s data as Base64 encoded string as a URL.

Realated Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">