Jan
15
2006
Uploading files
Posted by admin under
ASP.NET articles
While this article is placed in the upload subsection, it might not be the best place for ot. Because it's not a regular "how-to-upload- files-with-ASP.NET" article.
I might write such an article in the future but this is dealning with a problem you might encounter when using some sort of template-system on your site. I mean basically, all requests goes to a single ASPX page, such as default.aspx and depending on the context (for example sent in by a request variable) you load different user controls (ASCX) files.
For example:
default.aspx?page=start - might show start page
default.aspx?page=clientupload - might show a page when the client could upload a file to your server
Now, back to file upload. To upload a file you need to do two things:
1. Throw in a input type=file control
<INPUT class=textbox id=File1 type=file name=fileUploaded1 runat="server">
2. Set your forms enctype to multipart/form-data
<form enctype="multipart/form-data" runat="server">
Now what's the problem? Well some people might argue that it's no problem at all but the fact is that since you only have one single default.aspx file the form:s type will be always be multipart/form-data - even for the "start"-page. I won't get into that discussion but simple show you how to fix it
Lets say that page=start loads the ucStart.ascx user control. And page=ucClientUpload loads ucClientUpload.ascx
First remove the enctype="multipart/form-data" from the default.aspx form and open up ucClientUpload.ascx
What we are gonna do is from within ucClientUpload.ascx change the form enctype attribute:
protected void EnsureEncType()
{
System.Web.UI.Control oParent = Parent;
while( oParent != null && oParent.GetType() != typeof( System.Web.UI.HtmlControls.HtmlForm ) && oParent.GetType().FullName != "System.Web.UI.Page" )
{
oParent = oParent.Parent;
}
System.Web.UI.HtmlControls.HtmlForm oForm = oParent as System.Web.UI.HtmlControls.HtmlForm;
if ( oForm != null )
oForm.Enctype = "multipart/form-data";
}
And then just call EnsureEncType() from your Page_Load function. There you have it. Forms enctype set from within a usercontrol.
I'll be honest with you and say I didn't find out this myself, but it has been in my "toolbox" for quite a while and now when writing this article I was trying to look up who did it, but came up with a lot of chinese pages when googling. Anyway, just saying that so you understand that I don't take any credit for the solution, just trying to spread it.