Wednesday, February 4, 2009

Uploading Files using FileUpload control in Update Panel in ASP.Net AJAX

By default, FileUpload control will not work inside an UpdatePanel control for uploading files using Asynchronous postback. This is because, the file uploading and file manipulations is restricted by default in client side for security reasons. Hence it is not possible to upload files using asynchronous postback in UpdatePanel.

To upload files inside UpdatePanel control we need to rely upon a standard postback i.e. we need to set the button that is uploading the file to be PostBack trigger instead of AsyncPostBack trigger. This will initiate a normal postback whenever we click the upload button and it is possible to upload the file.
Refer the below code for clear understanding,

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
<asp:PostBackTrigger ControlID="btnUpload" />

protected void btnUpload_Click(object sender, EventArgs e)
string filename = System.IO.Path.GetFileName(fuUpload.FileName);
fuUpload.SaveAs("C:\temp" + filename);

No comments: