使用 Visual C# 將檔案上傳至網站

本文說明如何使用 Microsoft Visual C# 上傳檔案。

原始產品版本: Visual C#、ASP.NET、Internet Information Services
原始 KB 編號: 816150

簡介

本逐步解說文章討論如何將現有的映像檔案從本機硬碟上傳至網站。 輸入控制項可用來從本機電腦上傳影像。 正在上傳的這個檔案會向伺服器進行驗證,以確保您不會覆寫已上傳的現有檔案。 如果上傳的檔案存在於伺服器上,則會進行驗證。 本文使用表 EncType 單的 屬性來達成功能。

需求

本文假設您已熟悉下列主題:

  • Web 應用程式
  • ASP.NET

下列清單概述您需要的建議軟體和網路基礎結構:

  • Visual C# .NET 或 Visual C#
  • Internet Information Services (IIS)

建立 ASP.NET Web 表單

  1. 啟動 Visual Studio .NET 或 Visual Studio。

  2. [檔案] 功能表中,按一下 [新增],然後按一下 [專案]

    注意事項

    在 Visual Studio 中,指向 [檔案] 功能表上的 [新增],然後按兩下 [網站]

  3. [項目類型] 底下,按兩下 [Visual C# 專案]。 在 [範本] 底下,按兩下 [ASP.NET Web 應用程式]

    注意事項

    在 Visual Studio 中,選取 [語言] 右側的 [Visual C#]。 在 [範本] 底下,按兩下 [ASP.NET 網站]

  4. 在 [ 位置] 方 塊中,輸入下列位置,然後按兩下 [ 確定]
    http://WebServerName/ApplicationName

    注意事項

    WebServerName 是 Web 伺服器名稱的佔位元元。 ApplicationName 是應用程式名稱的佔位元。

    預設 會建立WebForm1.aspx

    注意事項

    在 Visual Studio 中,選取 [位置] 右邊的 [HTTP],然後輸入 <http://WebServerName>

  5. 在 [ 檢視] 功能表上,單擊 [HTML 來源]

    注意事項

    在 Visual Studio 中,單擊 [檢視] 功能表上的 [程序代碼]。

修改表單屬性

WebForm1HTML 視窗中,以下列內容取代表單標籤:

<form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">

屬性 EncType 會指定所張貼數據的格式。 瀏覽器會使用這個屬性來編碼張貼至伺服器的資訊。 此程式代碼中的動作屬性會指定頁面將處理要求。 根據預設,表單的方法屬性會設定為 post,讓您可以在交易中傳送大量數據。

新增輸入控制項以指定您要上傳至伺服器的檔案

  1. WebForm1HTML 視窗中,於開頭和結尾<form>標記之間新增下列程式代碼:

    <INPUT id="oFile" type="file" runat="server" NAME="oFile">
    

    此輸入控制項會指定您要上傳至伺服器的檔案。

  2. 您可以在控件前面新增文字字串,以提示使用者。 在 WebForm1HTML 視窗中,於輸入控件前面輸入下列文字:

    選取要上傳至伺服器的影像檔:

新增按鈕控制件

  1. WebForm1HTML 視窗中,於 [輸入] 控制程式程式代碼後面的開頭和結尾<form>標記之間新增下列程式代碼:

    <asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
    
  2. 此按鈕控制項可用來上傳您在輸入控制項中指定的檔案。

建立包含單一標籤的面板控制件以顯示輸出

WebForm1HTML 視窗中,於 [按鈕] 控制程式程式代碼後面的開頭和結尾<form>標記之間新增下列程式代碼:

<asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
    <asp:Label id="lblUploadResult" Runat="server"></asp:Label>
</asp:Panel>

此程式代碼用來顯示訊息,指出檔案上傳是否成功。 為了顯示此輸出,會建立包含單一卷標的面板控件。

在 Button Click 事件上上傳檔案

本節中的程式代碼會從本機文件系統擷取檔案、檢查檔案是否已存在於伺服器上,然後將檔案上傳至網站。 若要新增此程式代碼,請遵循下列步驟:

  1. Double-click the Upload button that was created in the Add a Button control section of this article to create an event handler for the Click event of the button control.

  2. 在[程序代碼] 視窗頂端新增下列程式 代碼

    using System.IO;
    
  3. 將下列程式代碼新增至 Click[上傳 ] 按鈕的事件處理程式:

    string strFileName;
    string strFilePath;
    string strFolder;
    strFolder = Server.MapPath("./");
    // Retrieve the name of the file that is posted.
    strFileName = oFile.PostedFile.FileName;
    strFileName = Path.GetFileName(strFileName);
    if(oFile.Value != "")
    {
        // Create the folder if it does not exist.
        if(!Directory.Exists(strFolder))
        {
            Directory.CreateDirectory(strFolder);
        }
        // Save the uploaded file to the server.
        strFilePath = strFolder + strFileName;
        if(File.Exists(strFilePath))
        {
            lblUploadResult.Text = strFileName + " already exists on the server!";
        }
        else
        {
            oFile.PostedFile.SaveAs(strFilePath);
            lblUploadResult.Text = strFileName + " has been successfully uploaded.";
        }
    }
    else
    {
        lblUploadResult.Text = "Click 'Browse' to select the file to upload.";
    }
    // Display the result of the upload.
    frmConfirmation.Visible = true;
    
  4. 在 [ 檔案] 功能表上,按兩下 [ 全部儲存]

確認上傳動作可運作

  1. 在 [ 偵錯] 功能表上,按兩下 [ 開始 ] 以建置並執行應用程式。 文本框和命令按鈕隨即出現。

  2. 在文字框中輸入圖像檔案的路徑,或按兩下 [ 瀏覽 ] 在本機電腦上尋找圖像檔案。

  3. 按兩下 [上傳 ] 將檔案傳送至伺服器。 如果檔案是唯一的,您會收到上傳成功的訊息。 如果檔案已經存在於伺服器上,您會收到適當的訊息。 您從此應用程式上傳的檔案會儲存在本機硬碟上的位置 C:\inetpub\wwwroot\ApplicationName

  4. 若要讓此應用程式在 .NET Framework 中運作,請允許 ASPNET 使用者的完全控制存取權。 如果要執行這項操作,請依照下列步驟執行:

    1. 在 Windows 檔案總管中找出應用程式資料夾。 路徑為 C:\inetpub\wwwroot\ApplicationName

    2. 以滑鼠右鍵按兩下 ApplicationName 資料夾,然後按下 [ 屬性]。 [ ApplicationName 屬性] 對話框隨即出現。

    3. 按一下 [安全性] 索引標籤。

    4. 按一下 [新增]。 [ 選取使用者或群組] 對話框隨即出現。

      注意事項

      在 Visual Studio 中,[ 選取使用者、計算機或群組 ] 對話框隨即出現。

    5. 在 [輸入要選取的物件名稱] 方塊中輸入 ASPNET,然後按兩下 [確定]

    6. 在 [ApplicationName 屬性] 對話框中,按兩下 [群組或使用者名稱] 清單中的 ASPNET 使用者。

    7. 在 [ 允許] 下,按兩下以選取 [ 完全控制] 複選框,然後按兩下 [ 確定]

完整的程式代碼清單

  • WebForm1.aspx

    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
       Inherits="Howto.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
       <HEAD>
          <title>WebForm1</title>
          <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
          <meta name="CODE_LANGUAGE" Content="C#">
          <meta name="vs_defaultClientScript" content="JavaScript">
          <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
       </HEAD>
       <body MS_POSITIONING="GridLayout">
          <form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">
             Image file to upload to the server: <INPUT id="oFile" type="file" runat="server" NAME="oFile">
             <asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
             <asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
                <asp:Label id="lblUploadResult" Runat="server"></asp:Label>
             </asp:Panel>
          </form>
       </body>
    </HTML>
    
  • WebForm1.aspx.cs

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.IO;
    namespace **ApplicationName** {
    /// <summary>
    /// Summary description for WebForm1.
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button btnUpload;
        protected System.Web.UI.WebControls.Label lblUploadResult;
        protected System.Web.UI.WebControls.Panel frmConfirmation;
        protected System.Web.UI.HtmlControls.HtmlInputFile oFile;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
        // Put user code to initialize the page here
        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion
    
        private void btnUpload_Click(object sender, System.EventArgs e)
        {
            string strFileName;
            string strFilePath;
            string strFolder;
            strFolder = Server.MapPath("./");
            // Get the name of the file that is posted.
            strFileName = oFile.PostedFile.FileName;
            strFileName = Path.GetFileName(strFileName);
            if(oFile.Value != "")
            {
                // Create the directory if it does not exist.
                if(!Directory.Exists(strFolder))
                {
                    Directory.CreateDirectory(strFolder);
                }
                // Save the uploaded file to the server.
                strFilePath = strFolder + strFileName;
                if(File.Exists(strFilePath))
                {
                    lblUploadResult.Text = strFileName + " already exists on the server!";
                }
                else
                {
                    oFile.PostedFile.SaveAs(strFilePath);
                    lblUploadResult.Text = strFileName + " has been successfully uploaded.";
                }
            }
            else
            {
                lblUploadResult.Text = "Click 'Browse' to select the file to upload.";
            }
            // Display the result of the upload.
            frmConfirmation.Visible = true;
        }
    }
    

注意事項

Visual Studio 中產生的程式代碼與 Visual Studio .NET 中產生的程式代碼不同。

疑難排解

  1. 在您安裝運行時間的路徑下方的 CONFIG 資料夾中,開啟位於您電腦上的Machine.config檔案。
  2. 尋找Machine.config<processModel> 檔案中的 區段,將 和 password 屬性變更user為您要 W3wp.exe 或 Aspnet_wp.exe 執行的使用者名稱和密碼,然後儲存 Machine.config 檔案。
  3. 找出 CONFIG 資料夾中的 [暫存 ASP.NET 檔案] 資料夾。 以滑鼠右鍵按兩下 [ 暫存 ASP.NET 檔案] 檔案 夾,然後按兩下 [ 內容]
  4. 在 [ 暫存 ASP.NET 檔案屬性 ] 對話框中,按兩下 [ 安全 性] 索引標籤。
  5. 按一下 [進階]
  6. 在 [暫存 ASP.NET 檔案的 存取控制 設定] 對話框中,按兩下 [新增]
  7. 在對話框的 [名稱] 方塊中輸入使用者名稱,然後按兩下 [確定]
  8. 在 [ 暫存 ASP.NET 檔案 的許可權專案] 對話框中,為使用者提供完整許可權,然後按兩下 [ 確定 ] 關閉 [ 暫存 ASP.NET 檔案屬性 ] 對話框。

參考資料