18.2. Uploading a File to the Web Server

Problem

You need to provide the ability for a user to upload a file to the web server filesystem.

Solution

Add to your page a FileUpload control and a button to initiate the upload process. When the user clicks the button, the code-behind can save the file to the filesystem.

Create a folder within your application file structure where the uploaded files will be placed, such as as one named uploads.

In the .aspx file:

  1. Add a FileUpload control.

  2. Add an Upload (or equivalently named) button.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Verify, in the Upload button click event handler, that the file content has been uploaded by checking the HasFile property of the FileUpload control.

  2. Save the file to the local filesystem on the server using the SaveAs method of the FileUpload object.

Example 18-4 shows the .aspx file for an application we’ve written to demonstrate this solution by allowing you to browse for a file and uploading the chosen file to your web server’s local filesystem when you click the Upload button. The code-behind files for the application are shown in Examples 18-5 (VB) and 18-6 (C#). The UI for uploading a file is shown in Figure 18-3.

UI for uploading a file

Figure 18-3. UI for uploading a file

Discussion

Most applications do not require uploading files to a web server. Nevertheless, here are a few examples of applications for which ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.