添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
public ref class FileUpload : System::Web::UI::WebControls::WebControl
[System.Web.UI.ControlValueProperty("FileBytes")]
[System.Web.UI.ValidationProperty("FileName")]
public class FileUpload : System.Web.UI.WebControls.WebControl
[<System.Web.UI.ControlValueProperty("FileBytes")>]
[<System.Web.UI.ValidationProperty("FileName")>]
type FileUpload = class
    inherit WebControl
Public Class FileUpload
Inherits WebControl
Object
FileUpload
  • 第一个示例演示如何创建一个 FileUpload 控件,用于将文件保存到代码中指定的路径。

  • 第二个示例演示如何创建一个 FileUpload 控件,用于将文件保存到应用程序的文件系统中的指定目录。

  • 第三个示例演示如何创建一个 FileUpload 控件,用于将文件保存到指定路径并限制可上传的文件的大小。

  • 第四个示例演示如何创建一个 FileUpload 控件,用于将文件保存到指定路径,并且仅允许上传具有.doc或.xls文件扩展名的文件。

    这些示例演示了控件的基本语法 FileUpload ,但它们并未演示保存文件之前应完成的所有必要错误检查。 有关更完整的示例,请参见 SaveAs

    以下示例演示如何创建一个 FileUpload 控件,用于将文件保存到代码中指定的路径。 SaveAs 调用 方法将文件保存到服务器上的指定路径。

    <%@ 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; // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html> <%@ 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 ' 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 xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>

    以下示例演示如何创建一个 FileUpload 控件,用于将文件保存到应用程序的文件系统中的指定目录。 属性 HttpRequest.PhysicalApplicationPath 用于获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。 SaveAs 调用 方法将文件保存到服务器上的指定路径。

    <%@ 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) // 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". string saveDir = @"\Uploads\"; // Get the physical file system path for the currently // executing application. string appPath = Request.PhysicalApplicationPath; // Before attempting to save the file, verify // that the FileUpload control contains a file. if (FileUpload1.HasFile) string savePath = appPath + saveDir + Server.HtmlEncode(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."; // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Class Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html> <%@ 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) ' 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 + _ Server.HtmlEncode(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." ' 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 xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Class Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>

    以下示例演示如何创建一个 FileUpload 控件,用于将文件保存到代码中指定的路径。 控件将可上载的文件的大小限制为 2 MB。 属性 PostedFile 用于访问基础 ContentLength 属性并返回文件的大小。 如果要上传的文件的大小小于 2 MB, SaveAs 则调用 方法将文件保存到服务器上的指定路径。 除了在应用程序代码中检查最大文件大小设置外,还可以将 httpRuntime 元素的 属性设置为 maxRequestLength 应用程序的配置文件中允许的最大大小。

    <%@ 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 save the file, verify // that the FileUpload control contains a file. if (FileUpload1.HasFile) // Get the size in bytes of the file to upload. int fileSize = FileUpload1.PostedFile.ContentLength; // Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded. if (fileSize < 2100000) // Append the name of the uploaded file to the path. savePath += Server.HtmlEncode(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."; // Notify the user why their file was not uploaded. UploadStatusLabel.Text = "Your file was not uploaded because " + "it exceeds the 2 MB size limit."; // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Class Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html> <%@ 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"> Protected 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 2,100,000 bytes (approximately 2 MB) to be uploaded. If (fileSize < 2100000) Then ' Append the name of the uploaded file to the path. savePath += Server.HtmlEncode(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." ' Notify the user why their file was not uploaded. UploadStatusLabel.Text = "Your file was not uploaded because " + _ "it exceeds the 2 MB size limit." End If ' 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 xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Class Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>

    以下示例演示如何创建一个 FileUpload 控件,用于将文件保存到代码中指定的路径。 此示例仅允许上传扩展名为 .doc 或 .xls 的文件。 Path.GetExtension 调用 方法可返回要上传的文件的扩展名。 如果文件具有.doc或.xls文件扩展名, SaveAs 则调用 方法将文件保存到服务器上的指定路径。

    <%@ 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 UploadBtn_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 save the file, verify // that the FileUpload control contains a file. if (FileUpload1.HasFile) // Get the name of the file to upload. string fileName = Server.HtmlEncode(FileUpload1.FileName); // Get the extension of the uploaded file. string extension = System.IO.Path.GetExtension(fileName); // Allow only files with .doc or .xls extensions // to be uploaded. if ((extension == ".doc") || (extension == ".xls")) // 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."; // 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."; </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Class Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html> <%@ 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"> Protected 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 = Server.HtmlEncode(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." ' 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 ' 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 xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>FileUpload Class Example</title> </head> <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> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>

    本主题内容:

  • 保存上传的文件

  • 安全注意事项

  • 将 FileUpload 控件与 UpdatePanel 控件配合使用

  • 声明性语法

    FileUpload 显示一个文本框控件和一个浏览按钮,使用户能够选择客户端上的文件并将其上传到 Web 服务器。 用户通过在本地计算机上输入文件的完整路径来指定要上传的文件 (例如,在控件的文本框中 C:\MyFiles\TestFile.txt ) 。 或者,用户可以通过单击“ 浏览 ”按钮,然后在“选择文件”对话框中查找文件来选择 该文件

    FileName 使用 属性获取客户端上使用 控件上传 FileUpload 的文件的名称。 此属性返回的文件名不包括客户端上的文件路径。

    属性 FileContent 获取指向 Stream 要上传的文件的 对象。 使用此属性以字节的形式访问文件的内容。 例如,可以使用 Stream 属性返回 FileContent 的 对象以字节的形式读取文件的内容,并将其存储在字节数组中。 或者,可以使用 FileBytes 属性检索文件中的所有字节。

    属性 PostedFile 获取要上传的文件的基础 HttpPostedFile 对象。 可以使用此属性访问文件上的其他属性。 属性 ContentLength 获取文件的长度。 属性 ContentType 获取文件的 MIME 内容类型。 此外,可以使用 PostedFile 属性访问 FileName 属性、 InputStream 属性和 SaveAs 方法。 但是,相同的功能由 FileName 属性、 FileContent 属性和 SaveAs 方法提供。

    保存上传的文件

    用户选择要上传的文件后,控件 FileUpload 不会自动将文件保存到服务器。 必须显式提供控件或机制,以允许用户提交指定的文件。 例如,可以提供用户单击以上传文件的按钮。 为保存指定文件而编写的代码应调用 SaveAs 方法,该方法将文件的内容保存到服务器上的指定路径。 通常, SaveAs 在事件处理方法中调用 方法,该事件将引发发回服务器。 例如,如果提供用于提交文件的按钮,则可以包含用于将文件保存在 click 事件的事件处理方法中的代码。

    在调用 SaveAs 方法将文件保存到服务器之前,请使用 HasFile 属性验证控件 FileUpload 是否包含文件。 HasFile 如果 返回 true ,则调用 SaveAs 方法。 如果返回 false ,则向用户显示一条消息,指示控件不包含文件。 不要检查 PostedFile 属性来确定是否存在要上传的文件,因为默认情况下,此属性包含 0 个字节。 因此,即使控件 FileUpload 为空,该属性也会 PostedFile 返回非 null 值。

    安全注意事项

    调用 SaveAs 方法时,必须指定要在其中保存上传文件的目录的完整路径。 如果未在应用程序代码中显式指定路径,当用户尝试上传文件时,将引发异常。 此行为通过阻止用户写入应用程序目录结构中的任意位置以及阻止访问敏感根目录,帮助保护服务器上的文件安全。

    方法 SaveAs 将上传的文件写入指定的目录。 因此,ASP.NET 应用程序必须对服务器上的目录具有写入访问权限。 应用程序可通过两种方式获取写入访问权限。 可以在保存上传文件的目录中显式授予对运行应用程序的帐户的写入访问权限。 或者,可以提高授予 ASP.NET 应用程序的信任级别。 若要获取对应用程序的执行目录的写入访问权限,必须将信任级别设置为 AspNetHostingPermissionLevel.Medium 值的对象授予 AspNetHostingPermission 应用程序。 提高信任级别会增加应用程序对服务器上的资源的访问权限。 请注意,这不是一种安全的方法,因为获得应用程序控制权的恶意用户也将能够在这种更高的信任级别下运行。 最佳做法是在用户的上下文中运行 ASP.NET 应用程序,具有运行应用程序所需的最低权限。 有关 ASP.NET 应用程序中的安全性的详细信息,请参阅 Web 应用程序和 ASP.NET 信任级别和策略文件 的基本安全做法

    防止拒绝服务攻击的一种方法是限制可以使用 FileUpload 控件上传的文件的大小。 应设置适合预期上传的文件类型的大小限制。 默认大小限制为 4096 KB) (KB,) 为 4 MB (MB。 可以通过设置 maxRequestLength httpRuntime 元素的 属性来允许上传较大的文件。 若要增加整个应用程序允许的最大文件大小,请在 Web.config 文件中设置 maxRequestLength 属性。 若要增加指定页面允许的最大文件大小,请在 Web.config 中的 元素内 location 设置 maxRequestLength 属性。有关示例,请参阅 location Element (ASP.NET Settings Schema)

    上传大型文件时,用户还可能收到以下错误消息:

    aspnet_wp.exe (PID: 1520) was recycled because memory consumption exceeded 460 MB (60 percent of available RAM).

    如果用户遇到此错误消息,请在应用程序的 Web.config 文件元素的 processModel 中增加 属性的值 memoryLimit 。 属性 memoryLimit 指定工作进程可以使用的最大内存量。 如果工作进程超过数量 memoryLimit ,则会创建一个新进程来替换该进程,并将所有当前请求重新分配给新进程。

    若要控制在处理请求时要上传的文件是暂时存储在内存中还是存储在服务器上,请设置 requestLengthDiskThreshold httpRuntime 元素的 属性。 使用此属性可以管理输入流缓冲区的大小。 默认值为 256 字节。 指定的值不应超过为 maxRequestLength 属性指定的值。

    将 FileUpload 控件与 UpdatePanel 控件配合使用

    FileUpload 控件设计为仅在回发方案中使用,而不是在部分页面呈现期间的异步回发方案中使用。 在 FileUpload 控件中使用 UpdatePanel 控件时,必须使用作为 PostBackTrigger 面板对象的控件上传文件。 UpdatePanel 控件用于更新页面的选定区域,而不是使用回发更新整个页面。 有关详细信息,请参阅 UpdatePanel 控件概述 分页呈现概述

    声明性语法

    <asp:FileUpload  
        AccessKey="string"  
        BackColor="color name|#dddddd"  
        BorderColor="color name|#dddddd"  
        BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|  
            Inset|Outset"  
        BorderWidth="size"  
        CssClass="string"  
        Enabled="True|False"  
        EnableTheming="True|False"  
        EnableViewState="True|False"  
        Font-Bold="True|False"  
        Font-Italic="True|False"  
        Font-Names="string"  
        Font-Overline="True|False"  
        Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|  
            Large|X-Large|XX-Large"  
        Font-Strikeout="True|False"  
        Font-Underline="True|False"  
        ForeColor="color name|#dddddd"  
        Height="size"  
        ID="string"  
        OnDataBinding="DataBinding event handler"  
        OnDisposed="Disposed event handler"  
        OnInit="Init event handler"  
        OnLoad="Load event handler"  
        OnPreRender="PreRender event handler"  
        OnUnload="Unload event handler"  
        runat="server"  
        SkinID="string"  
        Style="string"  
        TabIndex="integer"  
        ToolTip="string"  
        Visible="True|False"  
        Width="size"  
    
  •