Thursday, April 13, 2006
« .NET 2.0 Use IIS instead of the Developm... | Main | Poker »

I'm digging .NET 2.0! I can say for sure, that it's going to seem like forever waitng to switch over to it at work, but that's ok. So one of the things in .NET 1.1 that was decent, but could use improvement was client uploaded files via the browser.

Enter .NET 2.0 FileUpload Control. Now this may seem geeky, well, I guess if you are reading this you're either a friend, or a geek, so.... The coolest thing about the new 2.0 control is that you don't have to mess around withe MultiPart encded forms. Yep, this baby sits inside a 'normal' <form> tag. Wooooo!

And since it's now a <asp:> control type, you can run validators against it. No more making the user upload a file to determine if it's the correct type, or having to write javascript to check the input box. The really cool thing is that it just works.

Just add the following .aspx code

<asp:FileUpLoad id="FileUpLoad1" runat="server" />
<asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click" runat="server" Width="105px" />

Like I said you can even add Regex, Required Field, etc. validators and set the ControlToValidate argument to the name of your upload control.

Originally, in the codebehind I was doing this:

protected void UploadBtn_Click(object sender, EventArgs e)
{
   if
(FileUpLoad1.HasFile)
   {
      FileUpLoad1.SaveAs(FilePath
+ FileUpLoad1.FileName);
      //Then I was doing a bunch of GDI stuff to work on the image, sized it, and created a new image and saved it.
      //
The problem came when I wanted to delete the original as uploaded above.
      //snip
      
   }
}

Even after getting a handle to the file as an image, from the disk, AND calling the dispose method on the object when I was done with it, I'd still get an exception stating that the file was in use by another process when I was trying to delete the original.

So I talked w/ a guy at work here named Stuart (see blogroll on the right) and he mentioned that it would be good if I could work with it as a stream, instead of having to write it to the disk. So after some playing, I came up with this!

protected void UploadBtn_Click(object sender, EventArgs e)
{
   if
(FileUpLoad1.HasFile)
   {
      //Instead of saving the image, I just assign my variable to the Upload Control's instance of the file as a STREAM.
      System.Drawing.Image imgPhotoResize = System.Drawing.Image.FromStream(FileUploadControl.FileContent);
      
   }
}

Nice! Now there's no file to cleanup when I'm done, all I have to do is save the file from my Image object, and call Dispose() on my instance of that object:

   imgPhotoResize.Dispose();

Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):