Export (0) Print
Expand All

Uploading Files Using the File Field Control

 

By Bill Evjen
Reuters

Feburary 2004

Applies to:
    Microsoft® ASP.NET

Summary: Learn how to use the Microsoft ASP.NET File Field control to allow your end-users to upload one or more files to your server. (16 printed pages)

Contents

Introduction
Looking Closely at the File Field Control
   Working Around File Size Limitations
   Controlling Uploaded File Types
   Uploading Multiple Files at the Same Time
Conclusion
Related Books

Introduction

Microsoft® ASP.NET Web Forms are all about communicating with an end-user to abstract what information you need to from them depending on the service administered. In many cases with Web Forms, it is usually simply textual data that is collected and stored. However, there are many cases where you are going to need more than simple textual data; you may want your users to upload files to the server.

For instance, your application can have a document library that is shared with all users. There are plenty of examples, but invariably you will need this ability to upload any type of document for storage, or to have your application take action upon the document once it is uploaded.

In any case, ASP.NET provides you with a simple ability to upload documents to the server with just a little work on your part. This article describes how to use the File Field control for uploading documents to your Web server.

Looking Closely at the File Field Control

The File Field control uses the HtmlInputFile class and is a cool control simply because it does things that were difficult to do before ASP.NET (that is, without buying a third-party component to do it for you). The File Field control uploads files to the server from the client's machine.

It is important to note that this control is called the File Field control in all versions of Microsoft Visual Studio® .NET, while in the ASP.NET Web Matrix, this control is called the FileUpload control. In both cases, you will find the control in the HTML section of the Toolbox.

The File Field control allows access to program the HTML <input type="file"> tag. This tag is used to work with file data within an HTML form. In the past when using classic ASP (ASP 3.0 or earlier), many programmers worked with third-party components to upload files from the client to the server. Now, with .NET and this new control, uploading is taken care of for you—and it couldn't be simpler. Listing 1 shows you how to use the File Field control to upload files to the server.

Note   The sample code is provided in both Microsoft Visual Basic® (VB) and C#.

Listing 1. Uploading files to the server using the File Field control

VB

<%@ Page Language="VB" %>
<script runat="server">

    Sub SubmitButton_Click(Source As Object, e As EventArgs)
       If Not (File1.PostedFile Is Nothing) Then
          Try
             File1.PostedFile.SaveAs("C:\Uploads\uploadedfile.txt")
             Span1.InnerHtml = "Upload Successful!"
          Catch ex As Exception
             Span1.InnerHtml = "Error saving file <b>C:\\" & _
                File1.Value & "</b><br>" & ex.ToString()
          End Try
       End If
    End Sub

</script>
<html>
<head>
</head>
<body>
    <form runat="server" enctype="multipart/form-data">
        Select a file to upload:<br />
        <input type="file" id="File1" runat="Server">
        <p>
        <input type="submit" id="Submit1" runat="Server" 
         value="Upload File" OnServerClick="SubmitButton_Click">
        <p>
        <span id="Span1" runat="Server" />
    </form>
</body>
</html>

C#

<%@ Page Language="C#" %>
<script runat="server">

    void SubmitButton_Click(Object sender, EventArgs e) {
       if (File1.PostedFile != null) {
          try {
             File1.PostedFile.SaveAs("C:\\Uploads\\uploadedfile.txt");
             Span1.InnerHtml = "Upload Successful!";
          }
          catch (Exception ex) {
             Span1.InnerHtml = "Error saving file <b>C:\\" +
                File1.Value + "</b><br>" + ex.ToString();
          }
       }
    } 

</script>
<html>
<head>
</head>
<body>
    <form runat="server" enctype="multipart/form-data">
        Select a file to upload:<br />
        <input type="file" id="File1" runat="Server">
        <p>
        <input type="submit" id="Submit1" runat="Server" 
         value="Upload File" OnServerClick="SubmitButton_Click">
        <p>
        <span id="Span1" runat="Server" />
    </form>
</body>
</html>

When the page from Listing 1 is run, you can select a file and upload it to the server by clicking the Upload File button on the page. This is a great feature that ASP 3.0 programmers always wished for. Now it is here in .NET! With only a few lines of code, it is easy to upload any type of files to the server.

There are some important items we should go over for this example so you understand all the needed pieces to make this work. First, for the example in Listing 1 to work, you have to make the destination folder on the server writeable for the account used by ASP.NET so the file can be saved to the specified folder.

If you think your ASP.NET account is not enabled to write to the folder you want, simply open up Microsoft Windows® Explorer and navigate to the folder to which you want to add this permission. Right-click on the folder (in this case, the Uploads folder), and then select Properties. In the Properties dialog box, click on the Security tab and make sure the ASP.NET Machine Account is included in the list and has the proper permissions to write to disk (see Figure 1).

Aa478971.aspnet-fileupload_01(en-us,MSDN.10).gif

Figure 1. Looking at the Security tab of the Uploads folder

If you don't see the ASP.NET Machine Account under the Security tab, you can add it by clicking the Add button and entering ASPNET (without the period) in the text area, as illustrated in Figure 2.

Aa478971.aspnet-fileupload_02(en-us,MSDN.10).gif

Figure 2. Adding the ASP.NET Machine Account to the folder security definition

Click OK to add the ASP.NET Machine Account to the list. From here, make sure you give this account the proper permissions; then click OK and you are ready to go.

Looking at the code from Listing 1, you might notice some really important things right away. First, the <form> tag has been altered by the addition of another attribute. To upload files to a server, your <form> tag must have the attribute enctype="multipart/form-data". Without this attribute, the Web form cannot upload the file.

The Submit button on the page causes an OnServerClick event to occur. This event uploads the file and then displays a message telling you if the upload was successful. If it was unsuccessful, the page displays an error message describing why the upload failed.

By using the <input type="file"> tag, the browser automatically places a Browse button next to the text field on the ASP.NET page. You don't have to program anything else for this to occur. When the end user clicks the Browse button, he can navigate through the local file system to find the file to be uploaded to the server. This is shown in Figure 3. Clicking Open will place that filename and the file's path within the text field.

Aa478971.aspnet-fileupload_03(en-us,MSDN.10).gif

Figure 3. Choosing a file

Working Around File Size Limitations

You may not realize it, but there is a limit to the size of a file that can be uploaded using this technique. By default, the maximum size of a file to be uploaded to the server using the File Field control is around 4MB. You cannot upload anything that is larger than this limit.

One of the great things about .NET, however, is that it usually provides a way around limitations. You can usually change the default settings that are in place. To change this size limit, you make some changes in either the machine.config or web.config file.

In the machine.config file, find a node called <httpRuntime> that looks like the following:

<httpRuntime 
 executionTimeout="90" 
 maxRequestLength="4096"
 useFullyQualifiedRedirectUrl="false" 
 minFreeThreads="8" 
 minLocalRequestFreeThreads="4"
 appRequestQueueLimit="100"
/>

A lot is going on in this single node, but the setting that takes care of the size of the files to be uploaded is the maxRequestLength attribute. By default, this is set to 4096 kilobytes (KB). Simply change this value to increase the size of the files that you can upload to the server. If you want to allow 10 megabyte (MB) files to be uploaded to the server, set the maxRequestLength value to 11264, meaning that the application allows files that are up to 11000 KB to be uploaded to the server.

Making this change in the machine.config file applies this setting to all the applications that are on the server. If you want to apply this to only the application you are working with, then apply this node to the web.config file of your application, overriding any setting that is in the machine.config file. Make sure this node resides between the <system.web> nodes in the configuration file.

Another setting involved in the size limitation of files to be uploaded is the value given to the executionTimeout attribute in the <httpRuntime> node.

The value given the executionTimeout attribute is the number of seconds the upload is allowed to occur before being shut down by ASP.NET. If you are going to allow large files to be uploaded to the server, you are also going to want to increase this value along with the maxRequestLength value.

One negative with increasing the size of a file that can be uploaded is that there are hackers out there who attack servers by throwing a large number of requests at them. To guard against this, you can actually decrease the size of the files that are allowed to be uploaded; otherwise, you may find hundreds or even thousands of 10 MB requests hitting your server.

Controlling Uploaded File Types

There are a several methods you can use to control the types of files that are uploaded to the server. Unfortunately, there is no bullet-proof method to protect you from someone uploading files that would be considered malicious. You can take a few steps, however, to make this process of allowing end users to upload files a little more manageable.

One nice method you can employ is to use the ASP.NET validation controls that are provided for free with ASP.NET. These controls enable you to do a regular-expression check upon the file that is being uploaded to see if the extension of the file is one you permit to be uploaded.

This is ideal for browsers that allow client-side use of the validation controls because it forces the checking to be done on the client; the file is not uploaded to the server if the signature isn't one you allow. Listing 2 shows you an example of using validation controls to accomplish this task.

Note   The use of validation controls is not explained here. Take a look at Validating ASP.NET Server Controls for a complete explanation of validation controls and how to use them in your ASP.NET pages.

Listing 2: Using validation controls to restrict the types of files uploaded to the server

VB

<%@ Page Language="VB" %>
<script runat="server">

    Sub SubmitButton_Click(Source As Object, e As EventArgs)
       If Not (File1.PostedFile Is Nothing) Then
          Try
             File1.PostedFile.SaveAs("C:\Uploads\uploadedfile.txt")
             Span1.InnerHtml = "Upload Successful!"
          Catch ex As Exception
             Span1.InnerHtml = "Error saving file <b>C:\\" & _
                File1.Value & "</b><br>" & ex.ToString()
          End Try
       End If
    End Sub

</script>
<html>
<head>
</head>
<body>
    <form enctype="multipart/form-data" runat="server">
        <input id="File1" type="file" runat="Server" />
        <p>
            <input id="Submit1" type="submit" value="Upload File" 
             runat="Server" onserverclick="SubmitButton_Click" />
        </p>
        <span id="Span1" runat="Server" /> 
        <p>
            <asp:RegularExpressionValidator 
             id="RegularExpressionValidator1" runat="server" 
             ErrorMessage="Only mp3, m3u or mpeg files are 
             allowed!" ValidationExpression="^(([a-zA-
             Z]:)|(\\{2}\w+)\$?)(\\(\w[\w
             ].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$" 
             ControlToValidate="File1">
            </asp:RegularExpressionValidator>
            <br />
            <asp:RequiredFieldValidator 
             id="RequiredFieldValidator1" runat="server" 
             ErrorMessage="This is a required field!" 
             ControlToValidate="File1">
            </asp:RequiredFieldValidator>
        </p>        
    </form>
</body>
</html>

C#

<%@ Page Language="C#" %>
<script runat="server">

    void SubmitButton_Click(Object sender, EventArgs e) {
       if (File1.PostedFile != null) {
          try {
             File1.PostedFile.SaveAs("C:\\Uploads\\uploadedfile.txt");
             Span1.InnerHtml = "Upload Successful!";
          }
          catch (Exception ex) {
             Span1.InnerHtml = "Error saving file <b>C:\\" +
                File1.Value + "</b><br>" + ex.ToString();
          }
       }
    }

</script>
<html>
<head>
</head>
<body>
    <form enctype="multipart/form-data" runat="server">
        <input id="File1" type="file" runat="Server" />
        <p>
            <input id="Submit1" type="submit" value="Upload File" 
             runat="Server" onserverclick="SubmitButton_Click" />
        </p>
        <span id="Span1" runat="Server" /> 
        <p>
            <asp:RegularExpressionValidator 
             id="RegularExpressionValidator1" runat="server" 
             ErrorMessage="Only mp3, m3u or mpeg files are 
             allowed!" ValidationExpression="^(([a-zA-
             Z]:)|(\\{2}\w+)\$?)(\\(\w[\w
             ].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$" 
             ControlToValidate="File1">
            </asp:RegularExpressionValidator>
            <br />
            <asp:RequiredFieldValidator 
             id="RequiredFieldValidator1" runat="server" 
             ErrorMessage="This is a required field!" 
             ControlToValidate="File1">
            </asp:RequiredFieldValidator>
        </p>        
    </form>
</body>
</html>

This simple ASP.NET page uses validation controls so that the end user can only upload .mp3, .mpeg, or .m3u files to the server. If the file type is not one these three choices, a Validation control throws an exception onto the screen. This is shown in Figure 4.

Aa478971.aspnet-fileupload_04(en-us,MSDN.10).gif

Figure 4. Validating the file type using validation controls

Using validation controls is not a foolproof way of controlling the files that are uploaded to the server. It wouldn't be too hard for someone to change the file extension of a file so it would be accepted and uploaded to the server, thereby bypassing this simple security model.

Uploading Multiple Files at the Same Time

So far, you have seen some good examples of how to upload a file to the server without much hassle. Now let's 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.

One trick is to import the System.IO class into your ASP.NET page, and to then 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.

For this example, you can build an ASP.NET page that has four file-input boxes and one Submit button. 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 3).

Listing 3: Uploading multiple files to the server

VB

<%@ Import Namespace="System.IO" %>
<%@ Page Language="VB" %>

<script runat="server">

    Sub SubmitButton_Click(Source As Object, e As 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
                Span1.InnerHtml += "<u>File #" & (i+1) & "</u><br>"
                Span1.InnerHtml += "File Content Type: " & _
                   userPostedFile.ContentType & "<br>"
                Span1.InnerHtml += "File Size: " & _
                   userPostedFile.ContentLength & "kb<br>"
                Span1.InnerHtml += "File Name: " & _
                   userPostedFile.FileName & "<br>"
    
                userPostedFile.SaveAs(filepath & "\" & _
                   Path.GetFileName(userPostedFile.FileName))
    
                Span1.InnerHtml += "Location where saved: " & _
                   filepath & "\" & _
                   Path.GetFileName(userPostedFile.FileName) & _
                   "<p>"
             End If
          Catch ex As Exception
             Span1.InnerHtml += "Error:<br>" & ex.Message
          End Try
          i += 1
       Loop       
    End Sub

</script>

<html>
<head>
</head>
<body>
    <form enctype="multipart/form-data" runat="server">
        <p>
            Select File1:<br />
            <input id="File1" type="file" runat="Server" />
            <br />
            Select File2:<br />
            <input id="File2" type="file" runat="Server" />
            <br />
            Select File3:<br />
            <input id="File3" type="file" runat="Server" />
            <br />
            Select File4:<br />
            <input id="File4" type="file" runat="Server" />
        </p>
        <p>
            <input id="Submit1" type="submit" value="Upload Files" 
             runat="Server" onserverclick="SubmitButton_Click" />
            <br />
        </p>
        <span id="Span1" runat="Server"></span>
    </form>
</body>
</html>

C#

<%@ Import Namespace="System.IO" %>
<%@ Page Language="C#" %>

<script runat="server">

    protected void SubmitButton_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 )
             {
                Span1.InnerHtml += "<u>File #" + (i+1) + 
                   "</u><br>";
                Span1.InnerHtml += "File Content Type: " + 
                   userPostedFile.ContentType + "<br>";
                Span1.InnerHtml += "File Size: " + 
                   userPostedFile.ContentLength + "kb<br>";
                Span1.InnerHtml += "File Name: " + 
                   userPostedFile.FileName + "<br>";
    
                userPostedFile.SaveAs(filepath + "\\" + 
                   Path.GetFileName(userPostedFile.FileName));
    
                Span1.InnerHtml += "Location where saved: " + 
                   filepath + "\\" + 
                   Path.GetFileName(userPostedFile.FileName) + 
                   "<p>";
             }    
          } 
          catch (Exception Ex)
          {    
             Span1.InnerText += "Error: <br>" + Ex.Message;    
          }    
       }    
    }

</script>

<html>
<head>
</head>
<body>
    <form enctype="multipart/form-data" runat="server">
        <p>
            Select File1:<br />
            <input id="File1" type="file" runat="Server" />
            <br />
            Select File2:<br />
            <input id="File2" type="file" runat="Server" />
            <br />
            Select File3:<br />
            <input id="File3" type="file" runat="Server" />
            <br />
            Select File4:<br />
            <input id="File4" type="file" runat="Server" />
        </p>
        <p>
            <input id="Submit1" type="submit" value="Upload Files" 
             runat="Server" onserverclick="SubmitButton_Click" />
            <br />
        </p>
        <span id="Span1" runat="Server"></span>
    </form>
</body>
</html>

The end user can select up to four files and click the Upload Files button, which initializes the SubmitButton_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 5.

Aa478971.aspnet-fileupload_05(en-us,MSDN.10).gif

Figure 5. Uploading four files at once to the server from a single ASP.NET page

As you may have noticed, one interesting point about this example is that the states of the file input text boxes are not saved with the postback. You can see this in Figure 5. In ASP.NET, the state of the file-input text boxes cannot be saved because doing so might pose a security risk.

Conclusion

The File Field control provided by ASP.NET is a powerful control that was quite difficult to achieve in the days of Active Server Pages 3.0. This new capability allows your end-users to upload one or more files to your server. Remember, you can control the size of the files that are uploaded by working with settings in either the machine.config or web.config file.

Related Books

Show:
© 2014 Microsoft