按一下以給予評分及指教

  開啟低頻寬檢視
本頁僅適用於
Microsoft Visual Studio 2008/.NET Framework 3.5

其他版本也適用於下列軟體:
.NET Framework 類別庫
FileUpload 類別

更新:2007 年 11 月

顯示允許使用者選取要上載至伺服器之檔案的文字方塊控制項和瀏覽按鈕。

命名空間:  System.Web.UI.WebControls
組件:  System.Web (在 System.Web.dll 中)

Visual Basic (宣告)
<ControlValuePropertyAttribute("FileBytes")> _
<ValidationPropertyAttribute("FileName")> _
<AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
Public Class FileUpload _
    Inherits WebControl
Visual Basic (使用方式)
Dim instance As FileUpload
C#
[ControlValuePropertyAttribute("FileBytes")]
[ValidationPropertyAttribute("FileName")]
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class FileUpload : WebControl
Visual C++
[ControlValuePropertyAttribute(L"FileBytes")]
[ValidationPropertyAttribute(L"FileName")]
[AspNetHostingPermissionAttribute(SecurityAction::LinkDemand, Level = AspNetHostingPermissionLevel::Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction::InheritanceDemand, Level = AspNetHostingPermissionLevel::Minimal)]
public ref class FileUpload : public WebControl
J#
/** @attribute ControlValuePropertyAttribute("FileBytes") */
/** @attribute ValidationPropertyAttribute("FileName") */
/** @attribute AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal) */
/** @attribute AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal) */
public class FileUpload extends WebControl
JScript
public class FileUpload extends WebControl
ASP.NET
<asp:FileUpload />

FileUpload 類別會顯示文字方塊控制項和瀏覽按鈕,該控制項和按鈕可允許使用者選取用戶端上的檔案並將其上載至 Web 伺服器。使用者可藉由在控制項的文字方塊中輸入本機電腦上檔案的完整路徑 (例如,C:\MyFiles\TestFile.txt) 來指定要上載的檔案。或者,使用者也可以選取檔案,方法即按一下 [瀏覽] 按鈕,然後在 [選擇檔案] 對話方塊中尋找檔案。

注意事項:

FileUpload 控制項是專為在回傳案例中使用所設計,而不是在呈現部分網頁期間的非同步回傳案例中使用。當您在 UpdatePanel 控制項中使用 FileUpload 控制項時,必須使用本身為面板之 PostBackTrigger 物件的控制項上載檔案。UpdatePanel 控制項用來更新選取的網頁區域,而非使用回傳來更新整個網頁。如需詳細資訊,請參閱 UpdatePanel 控制項概觀網頁局部呈現概觀

在使用者選取要上載的檔案之後,FileUpload 控制項不會自動將檔案儲存至伺服器。您必須明確地提供控制項或機制,讓使用者送出指定的檔案。例如,您可以提供使用者可按一下以上載檔案的按鈕。您撰寫之用於儲存指定檔案的程式碼應該呼叫 SaveAs 方法,該方法會將檔案的內容儲存至伺服器上指定的路徑。通常,此控制項會呼叫在引發回傳至伺服器的事件之事件處理方法中的 SaveAs 方法。例如,如果您提供送出檔案的按鈕,則可以將儲存檔案的程式碼包含在按一下事件的事件處理方法中。

在呼叫 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 信任層級和原則檔

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 屬性指定的值。

TopicLocation
HOW TO:以 FileUpload Web 伺服器控制項上載檔案建置 ASP .NET Web 應用程式
HOW TO:以 FileUpload Web 伺服器控制項上載檔案在 Visual Studio 中建立 ASP .NET Web 應用程式
HOW TO:在 ASP.NET Web 伺服器控制項上設定焦點建置 ASP .NET Web 應用程式
HOW TO:在 ASP.NET Web 伺服器控制項上設定焦點在 Visual Studio 中建立 ASP .NET Web 應用程式

本節包含下列四個範例:

  • 第一個程式碼範例將示範如何建立 FileUpload 控制項,該控制項可將檔案儲存至程式碼中指定的路徑。

  • 第二個程式碼範例將示範如何建立 FileUpload 控制項,該控制項可將檔案儲存至應用程式之檔案系統中指定的目錄。

  • 第三個程式碼範例將示範如何建立 FileUpload 控制項,該控制項可將檔案儲存至指定的路徑並限制可上載之檔案的大小。

  • 第四個程式碼範例將示範如何建立 FileUpload 控制項,該控制項可將檔案儲存至指定的路徑並只允許上載副檔名為 .doc 或 .xls 的檔案。

警告:

這些程式碼範例會示範 FileUpload 控制項的基本語法,但不會示範儲存檔案之前應完成的所有必要錯誤檢查。如需更完整的範例,請參閱 SaveAs

在下列程式碼範例中,會示範如何建立 FileUpload 控制項,該控制項可將檔案儲存至程式碼中指定的路徑。此控制項會呼叫 SaveAs 方法,以將檔案儲存至伺服器上的指定路徑。

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

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)
  {
    // 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 方法,以將檔案儲存至伺服器上的指定路徑。

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

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)
    {
        // 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  >
<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 屬性設定為應用程式之組態檔中允許的最大大小。

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

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)
    {
        // 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  >
<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 方法,以將檔案儲存至伺服器上指定的路徑。

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

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

System..::.Object
  System.Web.UI..::.Control
    System.Web.UI.WebControls..::.WebControl
      System.Web.UI.WebControls..::.FileUpload
這個型別的任何 Public static (在 Visual Basic 中為 Shared) 成員都具備執行緒安全。並非所有的執行個體成員都是安全執行緒。

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework 和 .NET Compact Framework 並不支援各種平台的所有版本。如需支援平台版本的相關資訊,請參閱 .NET Framework 系統需求

.NET Framework

支援版本:3.5、3.0、2.0
社群內容   什麼是社群內容?
新增內容 RSS  註解
Processing
© 2009 Microsoft Corporation. 著作權所有,並保留一切權利。 使用規定  |  商標  |  隱私權聲明
Page view tracker