FileUpload上传控件用法详解来自MSDN帮助文档

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

注意:
FileUpload 控件设计为仅用于部分页面呈现期间的回发情况,并不用于异步回发情况。在 UpdatePanel 控件内部使用 FileUpload 控件时,必须通过一个控件来上载文件,该控件是面板的一个 PostBackTrigger 对象。UpdatePanel 控件用于更新页面的选定区域而不是使用回发更新整个页面。

解决方法如下:

<asp:ScriptManager ID="ScriptManager1" runat="server" />

</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /><br />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>

用户选择要上载的文件后,FileUpload 控件不会自动将该文件保存到服务器。您必须显式提供一个控件或机制,使用户能提交指定的文件。例如,可以提供一个按钮,用户单击它即可上载文件。为保存指定文件所写的代码应调用 SaveAs 方法,该方法将文件内容保存到服务器上的指定路径。通常,在引发回发到服务器的事件的事件处理方法中调用 SaveAs 方法。例如,如果提供一个用于提交文件的按钮,则可以放入一段代码,用于将该文件保存在单击事件的事件处理方法中。

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

调用 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 属性指定的值。

 

本节包含以下四个示例:

第一个示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。

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

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

第四个示例演示如何创建 FileUpload 控件,该控件将文件保存到指定路径并且只允许上载扩展名为 .doc 或 .xls 的文件。



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

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

C#   复制代码
<%@ 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)
{
   

    // 指定保存路径为c:\temp\uploads\

    String savePath = @"c:\temp\uploads\";

 

   

    // 用HasFile判断FileUpload1中是否存在文件

    if
(FileUpload1.HasFile)
    {
      // flieName保存上传的文件名称

      String fileName = FileUpload1.FileName;

      // SavePath指定上传的文件路径,注:这里保存的文件名称与原文件名称相同

      savePath += fileName;


      // 采用SaveAS保存文件

FileUpload1.SaveAs(savePath);



      


      // 采用UploadStatusLabel显示“文件已保存”


    
      UploadStatusLabel.Text = "Your file was saved as "
+ fileName;
    }
    else

    {     
      // 如果 FileUpload1无文件,则报错,无文件上传!

      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>

下面的示例演示如何创建 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>

 

下面的示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该控件将上载文件的大小限制为 5 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>

 

下面的示例演示如何创建 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>

 

原文地址:https://www.cnblogs.com/zzdxpq/p/2369851.html