Thursday, April 2, 2020

File Upload Thumbnail Preview using JQuery


In this tutorial we are going to see how to see the preview of the images once the image is selected using file upload.


Output:


Step 1: Download the latest jquery plugin.

Step 2: Create a Html page and paste the following code in it.


<div class="container">
        <h3>Fileupload Thumbnail</h3>
        <hr> 
<br/>
        <input type="file" id="myfileupload" multiple="multiple" accept=".jpg,.jpeg,.png"/>
        <br/>
        <h3>Preview</h3>
<hr>
<div id="imagePreview">
</div>
</div>


Step 3: Create a css/Styles.css file  and reference it under the head tag.


<link href="css/styles.css" rel="stylesheet" />


Paste the following code in the Style.css


@import url("https://fonts.googleapis.com/css?family=Open+Sans");

*{
    margin:0;
    padding: 0;
}

body{
    font-family: "Open sans";
    font-size: 14px;
}

.container{
    width:550px !important;
    margin: 25px auto;   
    padding: 5px; 
    border-radius: 10px;
}


 
    #canvas {
        width:2000px;
        height:2000px;
        border: 10px solid transparent;
    }
    .rectangle {
        border: 1px solid #FF0000;
        position: absolute;
    }
  
Step 3: Create a new script file js/fileupload.js and reference it after the jquery.


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


Paste the following code inside the fileupload.js


$(document).ready(function () {

$("#myfileupload").on("change",function(){
if(typeof(filereader) != undefined){
var imgprv = $("#imagePreview");
//clear the imagePreview div 
$("#imagePreview").html("");
$($(this)[0].files).each(function(){
var file = $(this);
var reader = new FileReader();
reader.onload = function(e){
var img = $("<img/>");
img.attr("src",e.target.result);
img.attr("style","height:200px;width:200px");
imgprv.append(img);
}
reader.readAsDataURL(file[0]);
});
}
else{
alert("Browser will not sport file reader");
}
});

});




No comments:

Post a Comment