Thursday, July 31, 2014

Preview image before upload using Jquery and save in asp.net

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

Description:


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

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></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.readAsDataURL(files[0]); 

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


<style>
#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;
}
</style>

Design page as shown below:

  <center>
   <fieldset style="width:35%">
   <legend>Preview Image before upload</legend>
   <table>
   <tr><td>Upload Image:</td><td>
       <asp:FileUpload ID="FileUpload1" runat="server" /><br />
       <asp:Label ID="lblmessage" runat="server"></asp:Label></td></tr>
       <tr><td></td><td><table><tr><td>
           <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>
   </table>        
      
   </fieldset>
   </center>

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;
                FileUpload1.SaveAs(path);
            }
            else
            {
                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
            FileUpload1.SaveAs(path)
        Else
            lblmessage.Text = "Select image to Upload"
        End If

    End Sub


Build the project and run.

Result:

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.

3 comments: