Powered by Blogger.

Sunday, February 16, 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:

- type is undefined scriptresource axd in AjaxControllToolkit

- What is the role of ScriptManager in Ajax?

- How to make scaling animation effect using AnimationExtender Control in asp.net

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.
<Triggers>
       <asp:PostBackTrigger ControlID="btnUpload1" />
</Triggers>

Implementation:
- 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.

<div>
    <fieldset style="width:300px;">
    <legend>Upload file example</legend>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    <table>
    <tr>
    <td>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <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" />
        </ContentTemplate>
       <Triggers>
       <asp:PostBackTrigger ControlID="btnUpload1" />
       </Triggers>
        </asp:UpdatePanel>
    </td>
    </tr>
    </table>
    </fieldset>    
    </div>

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);
            FileUpload1.SaveAs(ImgPath);
            string ShowImgPath = ImgPath.Substring(ImgPath.LastIndexOf("\\"));
            imgShow.ImageUrl = "~/Images" + ShowImgPath;
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Please select a specific image to upload');", true);                  
        }
    }



0 comments

Post a Comment