Preview Image before it is uploaded

Today we are going to learn about Image preview before it is uploaded.

In your php file, you have code as shown below:

<form id="form1" runat="server">
        <input type='file' id="uploadFile" />
        <img id="imagePreview" src="#" alt="your image" />

<script type="text/javascript" src="js/imagePreview.js"></script>
</form>

Include your script file in your header or footer, and you have js file with the name imagePreview as shown below:

$(function() {
    $("#uploadFile").on("change", function()
    {


        $( "#imagePreview" ).addClass( "giveImgStyle" );
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

        if (/^image/.test( files[0].type)){ // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file

            reader.onloadend = function(){ // set image data as background of div
                $("#imagePreview").css("background-image", "url("+this.result+")");
            }
        }
        else{
            alert('Please Select Image');
        }
    });
});


Then in your style sheet, add the style for giveImgStyle


.giveImgStyle{
    width: 180px;
    height: 180px;
    background-position: center center;
    background-size: cover;
    display: inline-block;
}

Then you are done. you get imagepreview as shown below

imagepreview

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s