Share via


ASP.NET: Development Tips And Tricks Part 1 - File Upload

ASP.NET provides built-in file upload support

· No posting acceptor required

· No third party components required

Accessible through two APIs:

· Request.Files collection

· <input type=file> server control

HttpPostedFile Object:

· HttpPostedFile.InputStream

· HttpPostedFile.ContentType

· HttpPostedFile.FileName

· HttpPostedFile.SaveAs(fileLocation)

There a couple of cool things that you can do now with the HTTPPostedFile object. You can actually get access to the raw bits that were uploaded using the InputSteam property. So if you want to do a virus check on the bits or write them to a different store you can do that too. You can also get the content type or mime type using the ContentType property. So, if you upload a Word document the ContentType will say “Application/MS Word” or if you upload an HTML file it will say “Text/HTML”. You can get the file name that was used on the client and lastly you can use the SaveAs method to easily save the posted file to disk on the server.

<html>

<script language="VB" runat=server>

Sub Btn_Click(Sender as Object, E as EventArgs)

UploadFile.PostedFile.SaveAs("c:\foo.txt")

End Sub

</script>

<body>

<form enctype="multipart/form-data" runat=server>

Select File To Upload:

<input id="UploadFile" type=file runat=server>

<asp:button OnClick="Btn_Click“ runat=server/>

</form>

</body>

</html>

This is a very simple file upload example. First, you’ll see that there is a form tag. To enable file upload, I need to add an enctype or “encoding type” to the form tag. This tells the browser to treat this form special by not just treating it as standared Uuencoded data, but make this a multipart/form data section. Next, there is a simple server control input ID = UploadFile type = file runat = server and a button server control to submit the form and act as the event handler. Basically, when I submit this form, my event handler will run and using the UploadFile server control, I’ll call the SaveAs method and save the file to disk on the server. You see that this doesn’t download anything special, that it’s just standard HTML to do file upload.

Next, we’ll look at saves a file directly to SQL and the file never has to touch the file system. First, we’ll post the file to the server and then access it as an array of bytes in memory without having to save it to disk. Then, we’ll write it into SQL as a BLOB using the Image data type. We’ll also save the ContentType and ContentLength of the file as well. What that will let me do is provide a simple edit link on another page and give me the option to download the file from the database, essentially creating a mini document management system. When someone clicks Open on the edit page, it’s going to automatically read the BLOB, set the proper content type and automatically download the file to the client without ever having to write anything to disk.