File Uploads and UpdatePanels

8/11/2008

ASP.Net's implementation of AJAX is pretty good with a couple of exceptions. Most of the issues are related to speed when it comes to UpdatePanels. However the issue that I'm going to bring up today is the fact that you can't place a FileUpload component inside of one.

The reason for this issue is pretty simple, you have to have a full post back in order to upload a file and javascript can't access files (well not without ActiveX, etc.). So what do we do? Well assuming that you can't move it out of the UpdatePanel for whatever reason, we have two options really. The first option is to register the item for full post back:

   1: ScriptManager.GetCurrent(Page).RegisterPostBackControl(NameOfUploadControl);

This is rather simple, but does cause a full post back. If that isn't an issue for you, then it's probably the easiest route to go. The second option is to put the FileUpload control (or input control) inside an iframe. In order to do this, we require two files obviously. All page one needs to include is:

   1: <iframe src="Page2.aspx"></iframe>

Obviously you'd want to set the width, etc as needed but that's it. The second page would then house the FileUpload control and a save button (note that you can also have the first page update the iframe and on post back have the second page save the file, but I'm just showing the easiest solution here). The second page then saves the item. So basically you'd have:

   1: <asp:FileUpload ID="FileUpload2" runat="server" />
   2: <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

for the front, and this for the back end:

   1: protected void Button1_Click(object sender, EventArgs e) 
   2: { 
   3:     FileUpload2.SaveAs("FileName"); 
   4: }

Note that you'd want some basic file checking, etc. in there but I'm just showing you the basic concept. Anyway, that's all there is to it. I'm currently using the second method to come up with an AJAX friendly system that will allow multiple file uploads and show the current progress.  When that's ready I'll be sure to post it here. Anyway, try out the code, leave feedback, and happy coding.



Comments