萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 列出伺服器目錄檔案並提供下載

功能需求

  • 掃描指定資料夾 (如 `~/uploads/`) 所有檔案。
  • 以 Repeater 列表顯示檔名。
  • 點擊下載時透過 `Response.WriteFile` 傳輸檔案。

完整程式碼

.aspx 頁面

<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
    <ItemTemplate>
        <div>
            <%# Eval("FileName") %>
            <asp:LinkButton ID="lnkDown" runat="server" CommandName="down" CommandArgument='<%# Eval("FileName") %>'>下載</asp:LinkButton>
        </div>
    </ItemTemplate>
</asp:Repeater>

.aspx.cs 後置碼

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) BindFiles();
}

private void BindFiles()
{
    string dirPath = Server.MapPath("~/uploads/");
    if (Directory.Exists(dirPath))
    {
        var dir = new DirectoryInfo(dirPath);
        var files = dir.GetFiles("*.*");
        var dt = new DataTable();
        dt.Columns.Add("FileName");
        foreach (var f in files)
            dt.Rows.Add(f.Name);
        Repeater1.DataSource = dt;
        Repeater1.DataBind();
    }
}

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "down")
    {
        try
        {
            string fileName = e.CommandArgument.ToString();
            string filepath = Server.MapPath("~/uploads/") + fileName;
            var fileInfo = new FileInfo(filepath);

            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", $"attachment; filename={HttpUtility.UrlEncode(fileInfo.Name, Encoding.UTF8)}");
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.Flush();
            Response.WriteFile(filepath); // 內建分塊傳輸,效能優於手動迴圈
            Response.End();
        }
        catch
        {
            Response.Write("<script>alert('找不到下載檔案')</script>");
        }
    }
}

關鍵點解析

  1. DirectoryInfo.GetFiles("*.*") 取得所有檔案,可改為 `"*.pdf"` 等過濾。
  2. `Response.WriteFile` 內部使用 `TransmitFile` (Kernel-mode cache),**不佔用 Managed Heap**,大檔效能優於 `BinaryWrite`/`OutputStream.Write`。
  3. `HttpUtility.UrlEncode(filename, Encoding.UTF8)` 解決中文檔名在 IE/Edge 下載時亂碼問題。
  4. `application/octet-stream` 強制瀏覽器彈出「另存新視窗」而非嘗試開啟。

安全性強化

  • 驗證 `fileName` 不含 `..`、`:`、`\` 等路徑遍歷字元。
  • 將上傳目錄設為 **非執行權限** (IIS Handler Mappings 移除 `*.aspx`、`*.ashx` 等)。
  • 生產環境建議改用資料庫儲存檔案中繼資料,實體檔案放在 Web Root 外部,下載時由後端 Stream 輸出。
copyright © 萬盛學電腦網 all rights reserved