首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 檔案下載三種實作方式

     編輯:關於ASP.NET

提供檔案下載是常見需求,本文整理三種主流做法。

1. 經典 ASP 風格

<%@ Page Language="C#" %>
<%
    string file = Request.QueryString["file"];
    if (string.IsNullOrEmpty(file)) { Response.Write("缺少 file 參數"); return; }

    string path = Server.MapPath(file);
    if (!System.IO.File.Exists(path)) { Response.Write("檔案不存在"); return; }

    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition", $"attachment; filename={Path.GetFileName(file)}");
    Response.TransmitFile(path); // 高效傳輸,不載入記憶體
    Response.End();
%>
  • 優點:簡單、支援大檔案(`TransmitFile` 直接發送)。
  • 缺點:`.aspx` 執行管線開銷、難以做權限檢查邏輯複用。

2. WebClient(伺服器端代理下載)

protected void btnDownload_Click(object sender, EventArgs e)
{
    using (var wc = new System.Net.WebClient())
    {
        // 將遠端檔案直接流向客戶端
        byte[] data = wc.DownloadData("https://remote-server/file.zip");
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=file.zip");
        Response.BinaryWrite(data);
    }
}
  • 適用:聚合多源下載、隱藏真實下載位址、需後端處理後再下發。
  • 缺點:大檔案會佔用伺服器記憶體,建議改用 `Stream` 分塊傳輸。

3. Generic Handler (.ashx) —— 推薦

public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string file = context.Request.QueryString["file"];
        // 權限檢查、日誌記錄...
        string path = context.Server.MapPath(file);
        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", $"attachment; filename={Path.GetFileName(file)}");
        context.Response.TransmitFile(path);
    }
    public bool IsReusable => false;
}
  • 輕量、無頁面生命週期開銷、易於複用權限邏輯、支援 `TransmitFile` 大檔案高效傳輸。
  • 註冊:``

大檔案斷點續傳支援

需處理 `Range` 標頭,回傳 `206 Partial Content`,建議使用成熟庫或 ASP.NET Core 內建 `PhysicalFileResult`/`FileStreamResult`。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved