ASP.NET Secrets, Part 2, Page 2
The Secrets to Uploading Files with Ease
In the golden, olden days of ASP, managing a file upload was pretty difficult. Most developers reverted to digging deep in their wallets to purchase a third-party add-on to help them achieve the desired result. No longer.
Thanks to the new ASP.NET features, you now can upload files with practically a few lines of code. And the following five, easy-to-follow steps show you exactly how to do it:
- Add a File Field control to your form. You'll find this under the HTML tab on the Toolbox. You'll have seen this control when uploading attachments through Hotmail, or when contributing files to a Web site.
- Right-click the File Field control and check the "Run as Server Control" option. This allows you to manipulate the control in code, sort of like a lesser-functional ASP.NET server control.
- Change the ID of your File Field control to something more understandable, such as "fileUpload".
- Enter the HTML view of your Web form and find the opening <form> tag. You'll need to edit this to add the parameter encType="multipart/form-data". Your <form> tag may look something like this when you're finished:
<form id="Form1" method="post" encType="multipart/form-data" _ runat="server">
Pretty simple, really. You might also want to check whether the user has uploaded a valid file first, before saving—unless you're really into errors. The following function does this for you, checking for null uploads and zero byte files:
Public Function FileFieldSelected(ByVal FileField As _ System.Web.UI.HtmlControls.HtmlInputFile) As Boolean ' Returns a True if the passed ' FileField has had a user post a file Dim intFileLength As Integer If FileField.PostedFile Is Nothing Then Return False If FileField.PostedFile.ContentLength = 0 Then Return False Return True End Function
Top Tip: If you get an access denied error when trying to save files directly to your Web application folder, go check your permissions. Ensure that your virtual directory in IIS has read and write permissions (change this through IIS). You may also want to ensure your ASPNET, Guest, or impersonated accounts have appropriate permissions, both for computer access and for the actual folder itself (right-click the folder, select 'Sharing and Security', then select the 'Security' tab).
The problem is that both you and I know that 95% of people reading this don't really want to go ahead and store files directly on the server file system. Rather, you want to go saving information into your database, into that SQL Server 'image' field.
Every article I've seen so far manages to conveniently skip this topic. And so does this one. But my book—VB.NET and ASP.NET Secrets—contains ready-to-run functions that handle this for you 100% automatically. If you're interested, check it out!
Caption: Click the button and pick a file!
Page 2 of 3