FileUpload 类

定义

显示一个文本框控件和一个浏览按钮,使用户可以选择要上载到服务器的文件。

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
继承
属性

示例

本主题附带了一个包含源代码的 Visual Studio 网站项目: 下载

本部分包含以下四个示例:

  • 第一个示例演示如何创建一个 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;
    }
    else
    {      
      // 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>
<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="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 xmlns="http://www.w3.org/1999/xhtml" >
<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="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.";

        }
        else
        {
            // 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>
<body>
    <h3>FileUpload Class Example: Save To Application Directory</h3>
    <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="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."

        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 xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Class Example</title>
</head>
<body>
   <h3>FileUpload Class Example: Save To Application Directory</h3>
   <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 控件,用于将文件保存到代码中指定的路径。 控件将可上载的文件的大小限制为 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.";
            }
            else
            {
                // Notify the user why their file was not uploaded.
                UploadStatusLabel.Text = "Your file was not uploaded because " + 
                                         "it exceeds the 2 MB size limit.";
            }
        }   
        else
        {
            // 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>
<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="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."
            
            Else
                ' 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
                
        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 xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Class 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 控件,用于将文件保存到代码中指定的路径。 此示例仅允许上传扩展名为 .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.";
            }
            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.";
            }

        }

    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Class 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="UploadBtn" 
            Text="Upload file"
            OnClick="UploadBtn_Click"
            runat="server">
        </asp:Button>    
       
        <hr />
       
        <asp:Label id="UploadStatusLabel"
            runat="server">
        </asp:Label>     
    </div>
    </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."
            
            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>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Class 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="UploadBtn" 
            Text="Upload file"
            OnClick="UploadBtn_Click"
            runat="server">
        </asp:Button>    
       
        <hr />
       
        <asp:Label id="UploadStatusLabel"
            runat="server">
        </asp:Label>     
    </div>
    </form>
</body>
</html>

注解

本主题内容:

介绍

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。 可以通过设置 maxRequestLengthhttpRuntime 元素的 属性来允许上传较大的文件。 若要增加整个应用程序允许的最大文件大小,请在 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 ,则会创建一个新进程来替换该进程,并将所有当前请求重新分配给新进程。

若要控制在处理请求时要上传的文件是暂时存储在内存中还是存储在服务器上,请设置 requestLengthDiskThresholdhttpRuntime 元素的 属性。 使用此属性可以管理输入流缓冲区的大小。 默认值为 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"  
/>  

构造函数

FileUpload()

初始化 FileUpload 类的新实例。

属性

AccessKey

获取或设置使您得以快速导航到 Web 服务器控件的访问键。

(继承自 WebControl)
Adapter

获取控件的浏览器特定适配器。

(继承自 Control)
AllowMultiple

获取或设置指定是否可选择多个文件用于上载的值。

AppRelativeTemplateSourceDirectory

获取或设置包含该控件的 PageUserControl 对象的应用程序相对虚拟目录。

(继承自 Control)
Attributes

获取与控件的特性不对应的任意特性(只用于呈现)的集合。

(继承自 WebControl)
BackColor

获取或设置 Web 服务器控件的背景色。

(继承自 WebControl)
BindingContainer

获取包含该控件的数据绑定的控件。

(继承自 Control)
BorderColor

获取或设置 Web 控件的边框颜色。

(继承自 WebControl)
BorderStyle

获取或设置 Web 服务器控件的边框样式。

(继承自 WebControl)
BorderWidth

获取或设置 Web 服务器控件的边框宽度。

(继承自 WebControl)
ChildControlsCreated

获取一个值,该值指示是否已创建服务器控件的子控件。

(继承自 Control)
ClientID

获取由 ASP.NET 生成的 HTML 标记的控件 ID。

(继承自 Control)
ClientIDMode

获取或设置用于生成 ClientID 属性值的算法。

(继承自 Control)
ClientIDSeparator

获取一个字符值,该值表示 ClientID 属性中使用的分隔符字符。

(继承自 Control)
Context

为当前 Web 请求获取与服务器控件关联的 HttpContext 对象。

(继承自 Control)
Controls

获取 ControlCollection 对象,该对象表示 UI 层次结构中的指定服务器控件的子控件。

(继承自 Control)
ControlStyle

获取 Web 服务器控件的样式。 此属性主要由控件开发人员使用。

(继承自 WebControl)
ControlStyleCreated

获取一个值,该值指示是否已为 Style 属性创建了 ControlStyle 对象。 此属性主要由控件开发人员使用。

(继承自 WebControl)
CssClass

获取或设置由 Web 服务器控件在客户端呈现的级联样式表 (CSS) 类。

(继承自 WebControl)
DataItemContainer

如果命名容器实现 IDataItemContainer,则获取对命名容器的引用。

(继承自 Control)
DataKeysContainer

如果命名容器实现 IDataKeysControl,则获取对命名容器的引用。

(继承自 Control)
DesignMode

获取一个值,该值指示是否正在使用设计图面上的一个控件。

(继承自 Control)
Enabled

获取或设置一个值,该值指示是否启用 Web 服务器控件。

(继承自 WebControl)
EnableTheming

获取或设置一个值,该值指示主题是否应用于该控件。

(继承自 WebControl)
EnableViewState

获取或设置一个值,该值指示服务器控件是否向发出请求的客户端保持自己的视图状态以及它所包含的任何子控件的视图状态。

(继承自 Control)
Events

获取控件的事件处理程序委托列表。 此属性为只读。

(继承自 Control)
FileBytes

从使用 FileUpload 控件指定的文件中获取一个字节数组。

FileContent

获取 Stream 对象,它指向要使用 FileUpload 控件上载的文件。

FileName

获取客户端上使用 FileUpload 控件上载的文件的名称。

Font

获取与 Web 服务器控件关联的字体属性。

(继承自 WebControl)
ForeColor

获取或设置 Web 服务器控件的前景色(通常是文本颜色)。

(继承自 WebControl)
HasAttributes

获取一个值,该值指示控件是否具有特性集。

(继承自 WebControl)
HasChildViewState

获取一个值,该值指示当前服务器控件的子控件是否具有任何已保存的视图状态设置。

(继承自 Control)
HasFile

获取一个值,该值指示 FileUpload 控件是否包含文件。

HasFiles

获取指示所有未见是否已经被上传的值。

Height

获取或设置 Web 服务器控件的高度。

(继承自 WebControl)
ID

获取或设置分配给服务器控件的编程标识符。

(继承自 Control)
IdSeparator

获取用于分隔控件标识符的字符。

(继承自 Control)
IsChildControlStateCleared

获取一个值,该值指示该控件中包含的控件是否具有控件状态。

(继承自 Control)
IsEnabled

获取一个值,该值指示是否启用控件。

(继承自 WebControl)
IsTrackingViewState

获取一个值,用于指示服务器控件是否会将更改保存到其视图状态中。

(继承自 Control)
IsViewStateEnabled

获取一个值,该值指示是否为该控件启用了视图状态。

(继承自 Control)
LoadViewStateByID

获取一个值,该值指示控件是否通过 ID 而不是索引参与加载其视图状态。

(继承自 Control)
NamingContainer

获取对服务器控件的命名容器的引用,此引用创建唯一的命名空间,以区分具有相同 ID 属性值的服务器控件。

(继承自 Control)
Page

获取对包含服务器控件的 Page 实例的引用。

(继承自 Control)
Parent

获取对页 UI 层次结构中服务器控件的父控件的引用。

(继承自 Control)
PostedFile

获取使用 FileUpload 控件上载的文件的基础 HttpPostedFile 对象。

PostedFiles

获取已上载文件的集合。

RenderingCompatibility

获取一个值,该值指定呈现的 HTML 将与之兼容的 ASP.NET 版本。

(继承自 Control)
Site

获取容器信息,该容器在呈现于设计图面上时承载当前控件。

(继承自 Control)
SkinID

获取或设置要应用于控件的外观。

(继承自 WebControl)
Style

获取将在 Web 服务器控件的外部标记上呈现为样式特性的文本特性的集合。

(继承自 WebControl)
SupportsDisabledAttribute

获取一个值,该值指示在控件的 disabled 属性为 IsEnabled 时,控件是否应将呈现的 HTML 元素的 false 特性设置为 "disabled"。

(继承自 WebControl)
TabIndex

获取或设置 Web 服务器控件的选项卡索引。

(继承自 WebControl)
TagKey

获取对应于此 Web 服务器控件的 HtmlTextWriterTag 值。 此属性主要由控件开发人员使用。

(继承自 WebControl)
TagName

获取控件标记的名称。 此属性主要由控件开发人员使用。

(继承自 WebControl)
TemplateControl

获取或设置对包含该控件的模板的引用。

(继承自 Control)
TemplateSourceDirectory

获取包含当前服务器控件的 PageUserControl 的虚拟目录。

(继承自 Control)
ToolTip

获取或设置当鼠标指针悬停在 Web 服务器控件上时显示的文本。

(继承自 WebControl)
UniqueID

获取服务器控件的唯一的、以分层形式限定的标识符。

(继承自 Control)
ValidateRequestMode

获取或设置指示控件是否检查来自浏览器的客户端输入是否具有潜在危险值的值。

(继承自 Control)
ViewState

获取状态信息的字典,这些信息使您可以在同一页的多个请求间保存和还原服务器控件的视图状态。

(继承自 Control)
ViewStateIgnoresCase

获取一个值,该值指示 StateBag 对象是否不区分大小写。

(继承自 Control)
ViewStateMode

获取或设置此控件的视图状态模式。

(继承自 Control)
Visible

获取或设置一个值,该值指示服务器控件是否作为 UI 呈现在页上。

(继承自 Control)
Width

获取或设置 Web 服务器控件的宽度。

(继承自 WebControl)

方法

AddAttributesToRender(HtmlTextWriter)

为指定的 HtmlTextWriter 对象添加 FileUpload 控件的 HTML 特性和样式,以在呈现内容时使用它们。

AddedControl(Control, Int32)

在子控件添加到 Control 对象的 Controls 集合后调用。

(继承自 Control)
AddParsedSubObject(Object)

通知服务器控件,分析了一个元素(XML 或 HTML),并将该元素添加到服务器控件的 ControlCollection 对象中。

(继承自 Control)
ApplyStyle(Style)

将指定样式的所有非空白元素复制到 Web 控件,覆盖控件的所有现有的样式元素。 此方法主要由控件开发人员使用。

(继承自 WebControl)
ApplyStyleSheetSkin(Page)

将页样式表中定义的样式属性应用到控件。

(继承自 Control)
BeginRenderTracing(TextWriter, Object)

开始输出数据的设计时追踪。

(继承自 Control)
BuildProfileTree(String, Boolean)

收集有关服务器控件的信息并将该信息发送到 Trace 属性,在启用页的跟踪功能时将显示该属性。

(继承自 Control)
ClearCachedClientID()

将缓存的 ClientID 值设置为 null

(继承自 Control)
ClearChildControlState()

删除服务器控件的子控件的控件状态信息。

(继承自 Control)
ClearChildState()

删除服务器控件的所有子控件的视图状态和控件状态信息。

(继承自 Control)
ClearChildViewState()

删除服务器控件的所有子控件的视图状态信息。

(继承自 Control)
ClearEffectiveClientIDMode()

将当前控件实例和任何子控件的 ClientIDMode 属性设置为 Inherit

(继承自 Control)
CopyBaseAttributes(WebControl)

Style 对象未封装的属性从指定的 Web 服务器控件复制到从中调用此方法的 Web 服务器控件。 此方法主要由控件开发人员使用。

(继承自 WebControl)
CreateChildControls()

由 ASP.NET 页框架调用,以通知服务器控件在准备回发或呈现时使用基于撰写的实现来创建其所包含任何子控件。

(继承自 Control)
CreateControlCollection()

创建一个新 ControlCollection 对象来保存服务器控件的子控件(包括文本控件和服务器控件)。

(继承自 Control)
CreateControlStyle()

创建由 WebControl 类在内部用来实现所有与样式有关的属性的样式对象。 此方法主要由控件开发人员使用。

(继承自 WebControl)
DataBind()

将数据源绑定到调用的服务器控件及其所有子控件。

(继承自 Control)
DataBind(Boolean)

将数据源绑定到调用的服务器控件及其所有子控件,同时可以选择引发 DataBinding 事件。

(继承自 Control)
DataBindChildren()

将数据源绑定到服务器控件的子控件。

(继承自 Control)
Dispose()

使服务器控件得以在从内存中释放之前执行最后的清理操作。

(继承自 Control)
EndRenderTracing(TextWriter, Object)

结束输出数据的设计时追踪。

(继承自 Control)
EnsureChildControls()

确定服务器控件是否包含子控件。 如果不包含,则创建子控件。

(继承自 Control)
EnsureID()

为尚未分配标识符的控件创建标识符。

(继承自 Control)
Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
FindControl(String)

在当前的命名容器中搜索带指定 id 参数的服务器控件。

(继承自 Control)
FindControl(String, Int32)

使用指定的 idpathOffset 参数(该参数有助于搜索)中指定的整数在当前命名容器中搜索服务器控件。 不应重写此版本的 FindControl 方法。

(继承自 Control)
Focus()

为控件设置输入焦点。

(继承自 Control)
GetDesignModeState()

获取控件的设计时数据。

(继承自 Control)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetRouteUrl(Object)

获取与一组路由参数对应的 URL。

(继承自 Control)
GetRouteUrl(RouteValueDictionary)

获取与一组路由参数对应的 URL。

(继承自 Control)
GetRouteUrl(String, Object)

获取与一组路由参数以及某个路由名称对应的 URL。

(继承自 Control)
GetRouteUrl(String, RouteValueDictionary)

获取与一组路由参数以及某个路由名称对应的 URL。

(继承自 Control)
GetType()

获取当前实例的 Type

(继承自 Object)
GetUniqueIDRelativeTo(Control)

返回指定控件的 UniqueID 属性的前缀部分。

(继承自 Control)
HasControls()

确定服务器控件是否包含任何子控件。

(继承自 Control)
HasEvents()

返回一个值,该值指示是否为控件或任何子控件注册事件。

(继承自 Control)
IsLiteralContent()

确定服务器控件是否只包含文字内容。

(继承自 Control)
LoadControlState(Object)

SaveControlState() 方法保存的上一个页请求还原控件状态信息。

(继承自 Control)
LoadViewState(Object)

从使用 SaveViewState() 方法保存的前一请求还原视图状态信息。

(继承自 WebControl)
MapPathSecure(String)

检索虚拟路径(绝对的或相对的)映射到的物理路径。

(继承自 Control)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MergeStyle(Style)

将指定样式的所有非空白元素复制到 Web 控件,但不覆盖该控件现有的任何样式元素。 此方法主要由控件开发人员使用。

(继承自 WebControl)
OnBubbleEvent(Object, EventArgs)

确定服务器控件的事件是否沿页的 UI 服务器控件层次结构向上传递。

(继承自 Control)
OnDataBinding(EventArgs)

引发 DataBinding 事件。

(继承自 Control)
OnInit(EventArgs)

引发 Init 事件。

(继承自 Control)
OnLoad(EventArgs)

引发 Load 事件。

(继承自 Control)
OnPreRender(EventArgs)

PreRender 控件引发 FileUpload 事件。

OnUnload(EventArgs)

引发 Unload 事件。

(继承自 Control)
OpenFile(String)

获取用于读取文件的 Stream

(继承自 Control)
RaiseBubbleEvent(Object, EventArgs)

将所有事件源及其信息分配给控件的父级。

(继承自 Control)
RemovedControl(Control)

Control 对象的 Controls 集合移除子控件后调用。

(继承自 Control)
Render(HtmlTextWriter)

FileUpload 控件内容发送到指定的 HtmlTextWriter 对象,该对象编写相应内容以便呈现在客户端。

RenderBeginTag(HtmlTextWriter)

将控件的 HTML 开始标记呈现到指定的编写器中。 此方法主要由控件开发人员使用。

(继承自 WebControl)
RenderChildren(HtmlTextWriter)

将服务器控件子级的内容输出到提供的 HtmlTextWriter 对象,该对象可写入要在客户端上呈现的内容。

(继承自 Control)
RenderContents(HtmlTextWriter)

将控件的内容呈现到指定的编写器中。 此方法主要由控件开发人员使用。

(继承自 WebControl)
RenderControl(HtmlTextWriter)

将服务器控件内容输出到所提供的 HtmlTextWriter 对象,如果启用了跟踪,则还将存储有关该控件的跟踪信息。

(继承自 Control)
RenderControl(HtmlTextWriter, ControlAdapter)

使用提供的 HtmlTextWriter 对象将服务器控件内容输出到提供的 ControlAdapter 对象。

(继承自 Control)
RenderEndTag(HtmlTextWriter)

将控件的 HTML 结束标记呈现到指定的编写器中。 此方法主要由控件开发人员使用。

(继承自 WebControl)
ResolveAdapter()

获取负责呈现指定控件的控件适配器。

(继承自 Control)
ResolveClientUrl(String)

获取浏览器可以使用的 URL。

(继承自 Control)
ResolveUrl(String)

将 URL 转换为在请求客户端可用的 URL。

(继承自 Control)
SaveAs(String)

将上载文件的内容保存到 Web 服务器上的指定路径。

SaveControlState()

保存将页面回发到服务器之后发生的所有服务器控件状态更改。

(继承自 Control)
SaveViewState()

保存调用 TrackViewState() 方法后修改的任何状态。

(继承自 WebControl)
SetDesignModeState(IDictionary)

为控件设置设计时数据。

(继承自 Control)
SetRenderMethodDelegate(RenderMethod)

分配事件处理程序委托,以将服务器控件及其内容呈现到父控件中。

(继承自 Control)
SetTraceData(Object, Object)

使用跟踪数据键和跟踪数据值,为呈现数据的设计时追踪设置跟踪数据。

(继承自 Control)
SetTraceData(Object, Object, Object)

使用跟踪对象、跟踪数据键和跟踪数据值,为呈现数据的设计时追踪设置跟踪数据。

(继承自 Control)
ToString()

返回表示当前对象的字符串。

(继承自 Object)
TrackViewState()

使控件跟踪其视图状态的更改,以便将这些更改存储在对象的 ViewState 属性中。

(继承自 WebControl)

事件

DataBinding

当服务器控件绑定到数据源时发生。

(继承自 Control)
Disposed

当从内存释放服务器控件时发生,这是请求 ASP.NET 页时服务器控件生存期的最后阶段。

(继承自 Control)
Init

当服务器控件初始化时发生;初始化是控件生存期的第一步。

(继承自 Control)
Load

当服务器控件加载到 Page 对象中时发生。

(继承自 Control)
PreRender

在加载 Control 对象之后、呈现之前发生。

(继承自 Control)
Unload

当服务器控件从内存中卸载时发生。

(继承自 Control)

显式接口实现

IAttributeAccessor.GetAttribute(String)

获取具有指定名称的 Web 控件的特性。

(继承自 WebControl)
IAttributeAccessor.SetAttribute(String, String)

将 Web 控件的特性设置为指定的名称和值。

(继承自 WebControl)
IControlBuilderAccessor.ControlBuilder

有关此成员的说明,请参见 ControlBuilder

(继承自 Control)
IControlDesignerAccessor.GetDesignModeState()

有关此成员的说明,请参见 GetDesignModeState()

(继承自 Control)
IControlDesignerAccessor.SetDesignModeState(IDictionary)

有关此成员的说明,请参见 SetDesignModeState(IDictionary)

(继承自 Control)
IControlDesignerAccessor.SetOwnerControl(Control)

有关此成员的说明,请参见 SetOwnerControl(Control)

(继承自 Control)
IControlDesignerAccessor.UserData

有关此成员的说明,请参见 UserData

(继承自 Control)
IDataBindingsAccessor.DataBindings

有关此成员的说明,请参见 DataBindings

(继承自 Control)
IDataBindingsAccessor.HasDataBindings

有关此成员的说明,请参见 HasDataBindings

(继承自 Control)
IExpressionsAccessor.Expressions

有关此成员的说明,请参见 Expressions

(继承自 Control)
IExpressionsAccessor.HasExpressions

有关此成员的说明,请参见 HasExpressions

(继承自 Control)
IParserAccessor.AddParsedSubObject(Object)

有关此成员的说明,请参见 AddParsedSubObject(Object)

(继承自 Control)

扩展方法

FindDataSourceControl(Control)

返回与指定控件的数据控件关联的数据源。

FindFieldTemplate(Control, String)

返回指定控件的命名容器中指定列的字段模板。

FindMetaTable(Control)

返回包含数据控件的元表对象。

适用于

另请参阅