Powered by Blogger.

Sunday, March 2, 2014

How to implement FileUpload Control in Update Panel using asp.net?

In this article we will discuss with example how to upload Image/ file through File Upload Control that will be inside Update Panel in asp.net.You can also check my previous article on:

- How to create dropdown menu for login and signup using jQuery in asp.net ?

- Show confirmation dialogbox using JavaScript in Asp.Net

- Create a database by command in sql server 2008

While implementing,we need to set the Button that is uploading the image to be "PostBackTrigger" instead of "AsyncPostBackTrigger". By setting so the upload button will cause the full post back and get and retain the image in the FileUpload control whenever clicked on.If you won't follow the same manytimes you will find that FileUpload control will not work properly in update panel.

To set the button as "PostBackTrigger".Mention like below.
       <asp:PostBackTrigger ControlID="btnUpload1" />

- In the (.aspx) page, place a FileUpload Control and a Button control and also place ScriptManager from the AJAX Extension category.

- create a folder in the root directory of your project and give it name “Images”. We will store our uploaded image in this folder.

    <fieldset style="width:300px;">
    <legend>Upload file example</legend>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload1" runat="server" Text="Upload"
                onclick="btnUpload1_Click" /><br />        
            <asp:Image ID="imgRaj" runat="server" Width="150px" />
       <asp:PostBackTrigger ControlID="btnUpload1" />

Code Behiend:
In the code behind file(.aspx.cs) write the code on the upload button’s click event as:
 protected void btnUpload1_Click(object sender, EventArgs e)
        if (FileUpload1.HasFile)
            string ImgPath = Server.MapPath("~/Images/" + Guid.NewGuid() +  FileUpload1.FileName);
            string ShowImgPath = ImgPath.Substring(ImgPath.LastIndexOf("\\"));
            imgShow.ImageUrl = "~/Images" + ShowImgPath;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Please select a specific image to upload');", true);