Monday, July 28, 2014

Image preview after upload in asp.net

Introduction: In this article today I will explain how we can preview the image after uploading in asp.net.

Description:


Add a webform to project and design the page as shown below:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
   <fieldset style="width:25%">
   <legend>Uplaod and Preview the Image</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> <asp:Button ID="btnupload" runat="server" Text="Upload Image"
           onclick="btnupload_Click" /></td></tr>
   </table>        
       <asp:Image ID="imgpreview" runat="server" width="350px" Height="300px"/>
   </fieldset>

   </center>
    </div>
    </form>
</body>
</html>

On button click write the below given code (C#):

   protected void btnupload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string path = Server.MapPath("~/Images/") + FileUpload1.FileName;
                FileUpload1.SaveAs(path);
                imgpreview.ImageUrl = "~/Images/" + FileUpload1.FileName;
            }
            else
            {
                lblmessage.Text = "Upload image";
                imgpreview.ImageUrl = "";
            }
        }

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)
            imgpreview.ImageUrl = "~/images/" + FileUpload1.FileName
        Else
            lblmessage.Text = "Upload Image"
            imgpreview.ImageUrl = ""
        End If

    End Sub


Build and run the project.

Output:

Image preview after upload in asp.net

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. 

1 comment:

  1. good !!! thnaks for all, please more more more :)!! thanks!!!

    ReplyDelete