Wednesday, 6 March 2013

File Upload in Update Panel




We know that we can upload file to server using File upload control. However, if we use file upload control inside update panel, then it doesn't work. The reason behind this is FileUpload control does not work with asynchronous postback.

Step1 :
Place ScriptManager control in .aspx page.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

Step 2:
Write the following source code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
  <asp:Button ID="BtnSubmit" runat="server" Text="Submit"  OnClick="BtnSubmit_Click" />
</ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="BtnSubmit" />
        </Triggers>
    </asp:UpdatePanel>

Step 3:
Add C # code
protected void BtnSubmit_Click(object sender, EventArgs e)
    {
if (FileUpload1.HasFile)
        {
            string imagename = Path.GetFileName(FileUpload1.PostedFile.FileName);
            FileUpload1.SaveAs(Server.MapPath("Images/" + imagename));
            string imagepath = Server.MapPath("Images/" + imagename);
            MySqlCommand cmd = new MySqlCommand("insert into table (Image)values('" + imagepath + "')", con);
            cmd.ExecuteNonQuery();
            con.Close();
           
        }
}

Step 4:
Add form Encryption Type to:

<form id="Form1" method="post" enctype="multipart/form-data" runat="server">

 You can also Use following code to set Encryption type by code behind:

C# code:
this.Page.Form.Enctype = "multipart/form-data";

No comments:

Post a Comment