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.
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
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
<%@ Page Language="VB" %>
<%@ Page Language="C#" %>
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).
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.
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
tag has been altered by the addition of another attribute. To upload files to a server, your
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
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.
Figure 3. Choosing a file
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 file, find a node called
that looks like the following:
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
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
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
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.
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
<%@ Page Language="VB" %>
<%@ Page Language="C#" %>
This simple ASP.NET page uses validation controls so that the end user can only upload
.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.
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.
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
<%@ Import Namespace="System.IO" %> <%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %> <%@ Page Language="C#" %>
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.
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.
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
来自 “ ITPUB博客 ” ，链接：http://blog.itpub.net/10771986/viewspace-966680/，如需转载，请注明出处，否则将追究法律责任。