注意:此类在 .NET Framework 2.0 版中是新增的。
显示一个文本框控件和一个浏览按钮,使用户可以选择要上载到服务器的文件。
命名空间:System.Web.UI.WebControls
程序集:System.Web(在 system.web.dll 中)
<ControlValuePropertyAttribute("FileBytes")> _ <ValidationPropertyAttribute("FileName")> _ Public Class FileUpload Inherits WebControl
Dim instance As FileUpload
[ControlValuePropertyAttribute("FileBytes")] [ValidationPropertyAttribute("FileName")] public class FileUpload : WebControl
[ControlValuePropertyAttribute(L"FileBytes")] [ValidationPropertyAttribute(L"FileName")] public ref class FileUpload : public WebControl
/** @attribute ControlValuePropertyAttribute("FileBytes") */ /** @attribute ValidationPropertyAttribute("FileName") */ public class FileUpload extends WebControl
ControlValuePropertyAttribute("FileBytes") ValidationPropertyAttribute("FileName") public class FileUpload extends WebControl
FileUpload 类显示一个文本框控件和一个浏览按钮,使用户可以选择客户端上的文件并将它上载到 Web 服务器。用户通过在控件的文本框中输入本地计算机上文件的完整路径(例如,C:/MyFiles/TestFile.txt)来指定要上载的文件。用户也可以通过单击“浏览”按钮,然后在“选择文件”对话框中定位文件来选择文件。
用户选择要上载的文件后,FileUpload 控件不会自动将该文件保存到服务器。您必须显式提供一个控件或机制,使用户能提交指定的文件。例如,可以提供一个按钮,用户单击它即可上载文件。为保存指定文件所写的代码应调用
在调用 SaveAs 方法将文件保存到服务器之前,使用 HasFile 属性来验证 FileUpload 控件确实包含文件。若 HasFile 返回 true,则调用 SaveAs 方法。如果它返回 false,则向用户显示消息,指示控件不包含文件。不要通过检查 PostedFile 属性来确定要上载的文件是否存在,因为默认情况下该属性包含 0 字节。因此,即使 FileUpload 控件为空,PostedFile 属性仍返回一个非空值。
调用 SaveAs 方法时,您必须指定用来保存上载文件的目录的完整路径。如果您没有在应用程序代码中显式指定路径,则当用户试图上载文件时将引发异常。该行为可防止用户在应用程序目录结构的任意位置进行写操作以及防止用户访问敏感的根目录,有助于确保服务器上文件的安全。
SaveAs 方法将上载的文件写到指定的目录。因此,ASP.NET 应用程序必须具有服务器上该目录的写访问权限。应用程序可以通过两种方式获得写访问权限。您可以将要保存上载文件的目录的写访问权限显式授予运行应用程序所使用的帐户。您也可以提高为 ASP.NET 应用程序授予的信任级别。若要使应用程序获得执行目录的写访问权限,必须将 AspNetHostingPermission 对象授予应用程序并将其信任级别设置为 AspNetHostingPermissionLevel.Medium 值。提高信任级别可提高应用程序对服务器资源的访问权限。请注意,该方法并不安全,因为如果怀有恶意的用户控制了应用程序,他(她)也能以更高的信任级别运行应用程序。最好的做法就是在仅具有运行该应用程序所需的最低特权的用户上下文中运行 ASP.NET 应用程序。有关 ASP.NET 应用程序中安全性的更多信息,请参见 Web 应用程序的基本安全实施策略 和 ASP.NET 信任级别和策略文件。
使用 FileName 属性来获取客户端上使用 FileUpload 控件上载的文件的名称。此属性返回的文件名不包含此文件在客户端上的路径。
FileContent 属性获取指向要上载的文件的 Stream 对象。使用该属性以字节方式访问文件内容。例如,可以使用 FileContent 属性返回的 Stream 对象以字节方式读取文件内容并将它们存储在一个字节数组中。也可以使用 FileBytes 属性来检索文件中的所有字节。
PostedFile 属性获取要上载的文件的基础 HttpPostedFile 对象。可以使用此属性访问文件的其他属性。ContentLength 属性获取文件的长度。ContentType 属性获取文件的 MIME 内容类型。此外,可以使用 PostedFile 属性来访问 FileName 属性、InputStream 属性和 SaveAs 方法。但是,FileName 属性、FileContent 属性和 SaveAs 方法也提供相同的功能。
防止拒绝服务攻击的方法之一是限制可以使用 FileUpload 控件上载的文件的大小。应当根据要上载的文件的类型,设置与类型相适应的大小限制。默认大小限制为 4096 KB (4 MB)。可以通过设置 httpRuntime 元素的 maxRequestLength 属性来允许上载更大的文件。若要增加整个应用程序所允许的最大文件大小,请设置 Web.config 文件中的 maxRequestLength 属性。若要增加指定页所允许的最大文件大小,请设置 Web.config 中 location 元素内的 maxRequestLength 属性。有关示例,请参见 location 元素(ASP.NET 设置架构)。
上载较大文件时,用户也可能接收到以下错误信息:
aspnet_wp.exe (PID: 1520) was recycled because memory consumption exceeded 460 MB (60 percent of available RAM).
若用户遇到此错误信息,请增加应用程序的 Web.config 文件的 processModel 元素中的 memoryLimit 属性的值。memoryLimit 属性指定了辅助进程可以使用的最大内存量。若辅助进程超出 memoryLimit 量,则创建一个新进程以替换它并将所有当前请求重新分配给新进程。
若要在处理请求时控制将要上载的文件是临时存储在内存中还是服务器上,请设置 httpRuntime 元素的 requestLengthDiskThreshold 属性。该属性使您能管理输入流缓冲区的大小。默认值为 256 个字节。您指定的值不应超出为 maxRequestLength 属性指定的值。
Topic | Location |
---|---|
如何:使用 FileUpload Web 服务器控件上载文件 | 生成 ASP .NET Web 应用程序 |
如何:在 ASP.NET Web 服务器控件上设置焦点 | 生成 ASP .NET Web 应用程序 |
本节包含四个代码示例:
-
第一个代码示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。
-
第二个代码示例演示如何创建 FileUpload 控件,该控件将文件保存到文件系统中针对应用程序的指定目录。
-
第三个代码示例演示如何创建 FileUpload 控件,该控件将文件保存到指定路径并限制上载文件的大小。
-
第四个代码示例演示如何创建 FileUpload 控件,该控件将文件保存到指定路径并且只允许上载扩展名为 .doc 或 .xls 的文件。
警告 |
---|
这些代码示例演示 FileUpload 控件的基本语法,但并没有演示保存文件之前应该完成的所有必要的错误检查。有关更完整的示例,请参见 SaveAs。 |
下面的代码示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Specify the path on the server to ' save the uploaded file to. Dim savePath As String = "c:/temp/uploads/" ' Before attempting to perform operations ' on the file, verify that the FileUpload ' control contains a file. If (FileUpload1.HasFile) Then ' Get the name of the file to upload. Dim fileName As String = FileUpload1.FileName ' Append the name of the file to upload to the path. savePath += fileName ' Call the SaveAs method to save the ' uploaded file to the specified path. ' This example does not perform all ' the necessary error checking. ' If a file with the same name ' already exists in the specified path, ' the uploaded file overwrites it. FileUpload1.SaveAs(savePath) ' Notify the user of the name the file ' was saved under. UploadStatusLabel.Text = "Your file was saved as " & fileName Else ' Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload." End If End Sub </script> <html > <head runat="server"> <title>FileUpload Example</title> </head> <body> <form id="form1" runat="server"> <div> <h4>Select a file to upload:</h4> <asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload> <br /><br /> <asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button> <hr /> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </div> </form> </body> </html>
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void UploadButton_Click(object sender, EventArgs e) { // Specify the path on the server to // save the uploaded file to. String savePath = @"c:/temp/uploads/"; // Before attempting to perform operations // on the file, verify that the FileUpload // control contains a file. if (FileUpload1.HasFile) { // Get the name of the file to upload. String fileName = FileUpload1.FileName; // Append the name of the file to upload to the path. savePath += fileName; // Call the SaveAs method to save the // uploaded file to the specified path. // This example does not perform all // the necessary error checking. // If a file with the same name // already exists in the specified path, // the uploaded file overwrites it. FileUpload1.SaveAs(savePath); // Notify the user of the name of the file // was saved under. UploadStatusLabel.Text = "Your file was saved as " + fileName; } else { // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; } } </script> <html > <head runat="server"> <title>FileUpload Example</title> </head> <body> <form id="form1" runat="server"> <div> <h4>Select a file to upload:</h4> <asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload> <br /><br /> <asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button> <hr /> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </div> </form> </body> </html>
下面的代码示例演示如何创建 FileUpload 控件,该控件将文件保存到文件系统中针对应用程序的指定目录。使用 HttpRequest.PhysicalApplicationPath 属性来获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="VB" %> <html> <head> <script runat="server"> Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Save the uploaded file to an "Uploads" directory ' that already exists in the file system of the ' currently executing ASP.NET application. ' Creating an "Uploads" directory isolates uploaded ' files in a separate directory. This helps prevent ' users from overwriting existing application files by ' uploading files with names like "Web.config". Dim saveDir As String = "/Uploads/" ' Get the physical file system path for the currently ' executing application. Dim appPath As String = Request.PhysicalApplicationPath ' Before attempting to save the file, verify ' that the FileUpload control contains a file. If (FileUpload1.HasFile) Then Dim savePath As String = appPath + saveDir + FileUpload1.FileName ' Call the SaveAs method to save the ' uploaded file to the specified path. ' This example does not perform all ' the necessary error checking. ' If a file with the same name ' already exists in the specified path, ' the uploaded file overwrites it. FileUpload1.SaveAs(savePath) ' Notify the user that the file was uploaded successfully. UploadStatusLabel.Text = "Your file was uploaded successfully." Else ' Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload." End If End Sub </script> </head> <body> <h3>FileUpload Class Example: Save To Application Directory</h3> <form ID="Form1" runat="server"> <h4>Select a file to upload:</h4> <asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload> <br><br> <asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button> <hr /> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>
下面的代码示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该控件将上载文件的大小限制为 5 MB。使用 PostedFile 属性来访问基础 ContentLength 属性并返回文件的大小。如果要上载的文件的大小小于 5 MB,则调用 SaveAs 方法将文件保存到服务器上的指定路径。除了检查应用程序代码中的最大文件大小设置之外,您还可以将 httpRuntime 元素的 maxRequestLength 属性设置为应用程序配置文件中所允许的最大大小。
<%@ Page Language="VB" %> <html> <head> <script runat="server"> Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Specify the path on the server to ' save the uploaded file to. Dim savePath As String = "c:/temp/uploads/" ' Before attempting to save the file, verify ' that the FileUpload control contains a file. If (FileUpload1.HasFile) Then ' Get the size in bytes of the file to upload. Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength ' Allow only files less than 5,100,000 bytes (approximately 5 MB) to be uploaded. If (fileSize < 5100000) Then ' Append the name of the uploaded file to the path. savePath += FileUpload1.FileName ' Call the SaveAs method to save the ' uploaded file to the specified path. ' This example does not perform all ' the necessary error checking. ' If a file with the same name ' already exists in the specified path, ' the uploaded file overwrites it. FileUpload1.SaveAs(savePath) ' Notify the user that the file was uploaded successfully. UploadStatusLabel.Text = "Your file was uploaded successfully." Else ' Notify the user why their file was not uploaded. UploadStatusLabel.Text = "Your file was not uploaded because " + _ "it exceeds the 5 MB size limit." End If Else ' Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload." End If End Sub </script> </head> <body> <h3>FileUpload Class Example: Check File Size</h3> <form ID="Form1" runat="server"> <h4>Select a file to upload:</h4> <asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload> <br><br> <asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button> <hr /> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>
下面的代码示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该示例只允许上载扩展名为 .doc 或 .xls 的文件。调用 Path.GetExtension 方法来返回要上载的文件的扩展名。如果文件扩展名为 .doc 或 .xls,则调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="VB" %> <html> <head> <script runat="server"> Sub UploadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Specify the path on the server to ' save the uploaded file to. Dim savePath As String = "c:/temp/uploads/" ' Before attempting to save the file, verify ' that the FileUpload control contains a file. If (FileUpload1.HasFile) Then ' Get the name of the file to upload. Dim fileName As String = FileUpload1.FileName ' Get the extension of the uploaded file. Dim extension As String = System.IO.Path.GetExtension(fileName) ' Allow only files with .doc or .xls extensions ' to be uploaded. If (extension = ".doc") Or (extension = ".xls") Then ' Append the name of the file to upload to the path. savePath += fileName ' Call the SaveAs method to save the ' uploaded file to the specified path. ' This example does not perform all ' the necessary error checking. ' If a file with the same name ' already exists in the specified path, ' the uploaded file overwrites it. FileUpload1.SaveAs(savePath) ' Notify the user that their file was successfully uploaded. UploadStatusLabel.Text = "Your file was uploaded successfully." Else ' Notify the user why their file was not uploaded. UploadStatusLabel.Text = "Your file was not uploaded because " + _ "it does not have a .doc or .xls extension." End If Else ' Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload." End If End Sub </script> </head> <body> <h3>FileUpload Class Example: Check File Extension</h3> <form ID="Form1" runat="server"> <h4>Select a file to upload:</h4> <asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload> <br><br> <asp:Button id="UploadBtn" Text="Upload file" OnClick="UploadBtn_Click" runat="server"> </asp:Button> <hr /> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.FileUpload