O'Reilly logo

ASP.NET 2.0: A Developer's Notebook by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Upload Files to Your Web Site

ASP.NET 2.0 now includes the FileUpload control, allowing web site users to upload files onto the web server for archival or file-submission purposes. For example, students typically need to upload their files to their school's server when they submit their assignment or project work. You'll find the FileUpload control in the Toolbox under the Standard tab.

Note

Uploading files to your web site is made easy with the new FileUpload control.

How do I do that?

The Visual Studio designer represents the FileUpload control by adding an empty text box and a Button control to a Web page. To upload the selected file, you need to explicitly trigger an event, such as clicking a button (see the Submit button in Figure 1-30). In the following example, you will build an application that allows users to upload files to a particular directory on the server. You will also check the size of the file uploaded to ensure that users do not upload files that exceed an imposed limit.

  1. Launch Visual Studio 2005 and create a new web site project. Name the project C:\ASPNET20\chap01-FileUpload.

  2. In the Toolbox, double-click the FileUpload control located under the Standard tab to add the control to the default Web Form, Default.aspx.

  3. Add a Button control to the default form, change its Text to "Submit", and name the button "btnSubmit".

  4. Your form should now look like the one shown in Figure 1-30.

    The FileUpload control on a Web Form

    Figure 1-30. The FileUpload control on a Web Form

    Note

    Remember to add a Submit button so that you can invoke the FileUpload control.

  5. Right-click the project name in Solution Explorer and then select Add Folder Regular Folder (see Figure 1-31). Name the new folder "uploads". This folder will be used to store the files uploaded by the user.

    Adding a new folder to the project

    Figure 1-31. Adding a new folder to the project

  6. Double-click the Submit button to reveal the code-behind. Enter the following code for the Submit button:

    Sub btnSubmit_Click(ByVal sender As Object, _
                        ByVal e As System.EventArgs) _
                        Handles btnSubmit.Click
        ' get the application path
        Dim savePath As String = Request.PhysicalApplicationPath
        ' uploads to a special upload folder
        savePath += "uploads\"
        If FileUpload1.HasFile Then ' verify if there is file to upload
            savePath += FileUpload1.FileName
            ' existing file will be overwritten
            FileUpload1.SaveAs(savePath)
            Response.Write("File uploaded successfully!")
        Else
            Response.Write("No file to upload")
        End If
    End Sub

Tip

You use the FileUpload1.SaveAs( ) method to save the file onto the specified directory. If there is a file of the same name, this method will simply overwrite it with the new file. Hence it is important that you do some error checking before writing the file to the server.

You find out the path that the current application resides in by using the PhysicalApplicationPath property from the Request object. The HasFile property of the FileUpload control specifies if the user has selected a file to upload. The file selected is saved in the FileName property of the FileUpload control.

What about...

...limiting the size of uploaded files?

For security reasons, it is important to restrict the size of files that users may upload to your web site. (Allowing users to upload a file that is too large could potentially expose an app to a denial-of-service attack.) You can check the size of the file uploaded by using the ContentLength property, as the following example shows:

Note

Be sure to check the size of the file that your user is trying to upload. Failing to do so may allow users to upload large files thereby slowing (or crashing) your web server.

' ensure size if below 3MB
If FileUpload1.PostedFile.ContentLength <= 3145728 Then
   savePath += FileUpload1.FileName
   ' existing file will be overwritten
   FileUpload1.SaveAs(savePath)
   Response.Write("File uploaded successfully!")
Else
   Response.Write("File size exceeds 3MB.")
End If

Where can I learn more?

If you want to learn more about how file uploading is done in ASP.NET 1.x, check out this article: http://www.ondotnet.com/pub/a/dotnet/2002/04/01/asp.html.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required