ASP.NET 2.0 FileUpload Server Control

In ASP.NET 1.0/1.1, you could upload files using the HTML FileUpload server control. This control put an <input type="file"> element on your Web page to enable the end user to upload files to the server. To use the file, however, you had to make a couple of modifications to the page. For example, you were required to add enctype="multipart/form-data" to the page’s <form> element.

ASP.NET 2.0 introduces a new FileUpload server control that makes the process of uploading files to a server even simpler. When giving a page the capability to upload files, you simply include the new <asp:FileUpload> control and ASP.NET takes care of the rest, including adding the enctype attribute to the page’s <form> element.

Uploading Files Using the FileUpload Control

After the file is uploaded to the server, you can also take hold of the uploaded file’s properties and either display them to the end user or use these values yourself in your page’s code behind. Listing 1 shows an example of using the new FileUpload control. The page contains a single FileUpload control, plus a Button and a Label control.

Listing 1: Uploading files using the new FileUpload control

VB

<%@ Page Language="VB"%>
<script runat="server">
   Protected Sub
   Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If FileUpload1.HasFile Then
            Try
                FileUpload1.SaveAs("C:\Uploads\" & _
                   FileUpload1.FileName)
                Label1.Text = "File name: " & _
                   FileUpload1.PostedFile.FileName & "<br>" & _
                   "File Size: " & _
                   FileUpload1.PostedFile.ContentLength & " kb<br>" & _
                   "Content type: " & _
                   FileUpload1.PostedFile.ContentType
            Catch ex As Exception
                Label1.Text = "ERROR: " & ex.Message.ToString()
            End Try
        Else
            Label1.Text = "You have not specified a file."
        End If
   End Sub

</script>
<html  >
<head runat="server">
    <title>FileUpload Server Control</title>
</head>
<body>
    <form id="form1" runat="server">

        <asp:FileUpload ID="FileUpload1" runat="server" />
        <p>
        <asp:Button ID="Button1" runat="server" Text="Upload"
         OnClick="Button1_Click" /></p>
        <p>
        <asp:Label ID="Label1" runat="server"></asp:Label></p>

    </form>
</body>
</html>

C#

<%@ Page Language="C#"%>
<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
           try {
              FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
              Label1.Text = "File name: " +
                   FileUpload1.PostedFile.FileName + "<br>" +
                   FileUpload1.PostedFile.ContentLength + " kb<br>" +
                   "Content type: " +
                   FileUpload1.PostedFile.ContentType;
           }
            catch (Exception ex) {
              Label1.Text = "ERROR: " + ex.Message.ToString();
            }
        else
        {
           Label1.Text = "You have not specified a file.";
        }
    }

</script>

From this example, you can see that the entire process is rather simple. The single button on the page initiates the upload process. The FileUpload control itself does not initiate the uploading process. You must initiate it through another event such as Button_Click.

When compiling and running this page, you may notice a few things in the generated source code of the page. An example of the generated source code is presented here:

<html  >
<head id="Head1"><title>
      FileUpload Server Control
</title></head>

<body>
    <form name="form1" method="post" action="FileUpload.aspx" id="form1"
     enctype="multipart/form-data">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
 value="/wEPDwUKMTI3ODM5MzQ0Mg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm
 0tZGF0YWRkrSpgAFaEKed5+5/8+zKglFfVLCE=" />
</div>
   <input type="file" name="FileUpload1" id="FileUpload1" />
   <p>

   <input type="submit" name="Button1" value="Upload" id="Button1" /></p>
   <p>
   <span id="Label1"></span></p>

<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
 value="/wEWAgL1wLWICAKM54rGBqfR8MhZIDWVowox+TUvybG5Xj0y" />

</div></form>
</body>
</html>

The first thing to notice is that because the FileUpload control is on the page, ASP.NET 2.0 modified the page’s <form> element on your behalf by adding the appropriate enctype attribute. Also notice that the FileUpload control was converted to an HTML <input type="file"> element.

After the file is uploaded, the first check (done in the file’s Button1_Click event handler) examines whether a file reference was actually placed within the <input type="file"> element. If a file was specified, an attempt is made to upload the referenced file to the server using the SaveAs method of the FileUpload control. That method takes a single String parameter, which should include the location where you want to save the file. In the String parameter used in Listing 1, you can see that the file is being saved to a folder called Uploads, which is located in the C:\ drive.

The PostedFile.FileName attribute is used to give the saved file the same name as the file it was copied from. If you want to name the file something else, simply use the SaveAs method in the following manner:

FileUpload1.SaveAs("C:\Uploads\UploadedFile.txt")

You could also give the file a name that specifies the time it was uploaded:

FileUpload1.SaveAs("C:\Uploads\" &
   System.DateTime.Now.ToFileTimeUtc() & ".txt")

After the upload is successfully completed, the Label control on the page is populated with metadata of the uploaded file. In the example, the file’s name, size, and content type are retrieved and displayed on the page for the end user. When the file is uploaded to the server, the page generated is similar to that shown in Figure 1.

Figure 1

Uploading files to another server can be an error-prone affair. It is vital to upload files in your code using proper exception handling. That’s why the file in the example is uploaded using a Try Catch statement.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read