Thursday, July 31, 2014

Preview image before upload using Jquery and save in

Introduction: In this article today I will explain how we can preview the image before upload and save in


Add a webform to project. After add the below given script and style to head section of page:

<script type="text/javascript" src=""></script>
    <script type="text/javascript">
$(function() {
    $("#FileUpload1").on("change", function ()
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return;

        if (/^image/.test( files[0].type)){ 
            var reader = new FileReader(); 

            reader.onloadend = function(){ 
                $("#imagePreview").css("background-image", "url(" + this.result + ")");

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

Design page as shown below:

   <fieldset style="width:35%">
   <legend>Preview Image before upload</legend>
   <tr><td>Upload Image:</td><td>
       <asp:FileUpload ID="FileUpload1" runat="server" /><br />
       <asp:Label ID="lblmessage" runat="server"></asp:Label></td></tr>
           <asp:Image ID="imagePreview" runat="server" /></td></tr></table></td></tr>
   <tr><td></td><td> <asp:Button ID="btnupload" runat="server" Text="Upload Image"
           onclick="btnupload_Click" /></td></tr>

Now on button click event write the given code (C#):

protected void btnupload_Click(object sender, EventArgs e)
            if (FileUpload1.HasFile)
                string path = Server.MapPath("~/Images/") + FileUpload1.FileName;
                lblmessage.Text = "Select image to Upload";

In VB:

Protected Sub btnupload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnupload.Click
        Dim path As String
        If FileUpload1.HasFile Then
            path = Server.MapPath("~/images/") + FileUpload1.FileName
            lblmessage.Text = "Select image to Upload"
        End If

    End Sub

Build the project and run.


Preview image before upload

Is this article helpful for you?
If yes post your comment to appreciate my work and fell free to contact me. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.