Wrox Home  
Search
Professional ASP.NET 2.0 Special Edition
by Bill Evjen, Scott Hanselman, Devin Rader, Farhan Muhammad, Srinivasa Sivakumar
October 2006, Hardcover


Uploading Multiple Files from the Same Page

So far, you have seen some good examples of how to upload a file to the server without much hassle. Now, take a look at how to upload multiple files to the server from a single page.

No built-in capabilities in the Microsoft .NET Framework enable you to upload multiple files from a single ASP.NET page. With a little work, however, you can easily accomplish this task just as you would have in the past using .NET 1.x.

The trick is to import the System.IO class into your ASP.NET page and then to use the HttpFileCollection class to capture all the files that are sent in with the Request object. This approach enables you to upload as many files as you want from a single page.

If you wanted to, you could simply handle each and every FileUpload control on the page individually as shown in in Listing 3.

Listing 3: Handling each FileUpload control individually

VB

If FileUpload1.HasFile Then
   ' Handle file
End If
If FileUpload2.HasFile Then
   ' Handle file
End If

C#

if (FileUpload1.HasFile) {
   // Handle file
}
if (FileUpload2.HasFile) {
   // Handle file
}

If you are working with a limited number of file upload boxes, this approach works; but at the same time you may, in certain cases, want to handle the files using the HttpFileCollection class. This is especially true if you are working with a dynamically generated list of server controls on your ASP.NET page.

For an example of this, you can build an ASP.NET page that has three FileUpload controls and one Submit button (using the Button control). After the user clicks the Submit button and the files are posted to the server, the code behind takes the files and saves them to a specific location on the server. After the files are saved, the file information that was posted is displayed in the ASP.NET page (see Listing 4).

Listing 4: Uploading multiple files to the server

VB

Protected Sub Button1_Click(ByVal sender As Object, _
   ByVal e As System.EventArgs)
   Dim filepath As String = "C:\Uploads"
   Dim uploadedFiles As HttpFileCollection = Request.Files
   Dim i As Integer = 0
   Do Until i = uploadedFiles.Count
     Dim userPostedFile As HttpPostedFile = uploadedFiles(i)
     Try
        If (userPostedFile.ContentLength > 0) Then
           Label1.Text += "<u>File #" & (i + 1) & "</u><br>"
           Label1.Text += "File Content Type: " & _
              userPostedFile.ContentType & "<br>"
           Label1.Text += "File Size: " & _
              userPostedFile.ContentLength & "kb<br>"
           Label1.Text += "File Name: " & _
              userPostedFile.FileName & "<br>"
           userPostedFile.SaveAs(filepath & "\" & _
              System.IO.Path.GetFileName(userPostedFile.FileName))
           Label1.Text += "Location where saved: " & _
              filepath & "\" & _
              System.IO.Path.GetFileName(userPostedFile.FileName) & _
              "<p>"
        End If
     Catch ex As Exception
        Label1.Text += "Error:<br>" & ex.Message
     End Try
     i += 1
   Loop
End Sub

C#

protected void Button1_Click(object sender, EventArgs e)
{
   string filepath = "C:\\Uploads";
   HttpFileCollection uploadedFiles = Request.Files;
    
   for (int i = 0; i < uploadedFiles.Count; i++)
   {    
      HttpPostedFile userPostedFile = uploadedFiles[i];
    
      try
      {    
         if (userPostedFile.ContentLength > 0 )
         {
            Label1.Text += "<u>File #" + (i+1) + 
               "</u><br>";
            Label1.Text += "File Content Type: " + 
               userPostedFile.ContentType + "<br>";
            Label1.Text += "File Size: " + 
               userPostedFile.ContentLength + "kb<br>";
            Label1.Text += "File Name: " + 
               userPostedFile.FileName + "<br>";
    
            userPostedFile.SaveAs(filepath + "\\" + 
               System.IO.Path.GetFileName(userPostedFile.FileName));
    
            Label1.Text += "Location where saved: " + 
               filepath + "\\" + 
               System.IO.Path.GetFileName(userPostedFile.FileName) + 
               "<p>";
         }    
      } 
      catch (Exception Ex)
      {    
         Label1.Text += "Error: <br>" + Ex.Message;    
      }    
   }    
}

This ASP.NET page enables the end user to select up to three files and click the Upload Files button, which initializes the Button1_Click event. Using the HttpFileCollection class with the Request.Files property lets you gain control over all the files that are uploaded from the page. When the files are in this state, you can do whatever you want with them. In this case, the files' properties are examined and written to the screen. In the end, the files are saved to the Uploads folder in the root directory of the server. The result of this action is illustrated in Figure 4.

Professional ASP.NET 2.0 Special Edition - Figure 4
Figure 4

This excerpt is from Chapter 6 "ASP.NET 2.0 Web Server Controls" of the upcoming (Sept-2006) Professional ASP.NET 2.0 Special Edition, which is the expanded edition of the best selling ASP.NET 2.0 book Professional ASP.NET 2.0. This new expanded Special Edition adds approximately 300 pages of new content plus updates throughout the book. Bill Evjen (St. Louis, MO) is one of the most active proponents of the .NET technologies. He has been involved with .NET since 2000 and has since become the founder and president of the International .NET Association (www.ineta.org) representing nearly 500,000 members worldwide. In addition to working in the .NET world, Bill is a Technical Director serving in the office of the Chief Scientist for the international news and financial services company Reuters. Bill is the lead co-author of the upcoming (Sept-2006) Professional ASP.NET 2.0 Special Edition and the best selling ASP.NET 2.0 book Professional ASP.NET 2.0.