FileUpload上傳控件用法詳解

FileUpload 類顯示一個文本框控件和一個瀏覽按鈕,使用戶可以選擇客戶端上的文件並將它上載到 Web 服務器。用戶通過在控件的文本框中輸入本地計算機上文件的完整路徑(例如,C:\MyFiles\TestFile.txt )來指定要上載的文件。用戶也可以通過單擊“瀏覽” 按鈕,然後在“選擇文件” 對話框中定位文件來選擇文件。

注意:
FileUpload 控件設計爲僅用於部分頁面呈現期間的回發情況,並不用於異步回發情況。在 UpdatePanel 控件內部使用 FileUpload 控件時,必須通過一個控件來上載文件,該控件是面板的一個 PostBackTrigger 對象。UpdatePanel 控件用於更新頁面的選定區域而不是使用回發更新整個頁面。

解決方法如下:

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

<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 方法將文件保存到服務器上的指定路徑。


<%@ 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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章