萬盛學電腦網

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

ASP.NET 檔案下載三種實作:從簡單到串流傳輸

方式一:傳統 ASP 風格(不推薦)

<% 
  string filename = Request.QueryString["FileName"];
  if (string.IsNullOrEmpty(filename)) return;
  Response.ContentType = "application/octet-stream";
  Response.AddHeader("content-disposition", $"attachment; filename={filename}");
  var fs = new ADODB.Stream(); // 需 COM 參考,已過時
  fs.Type = 1; fs.Open(); fs.LoadFromFile(Server.MapPath(filename));
  Response.BinaryWrite(fs.Read());
  fs.Close();
%>

缺點:依賴 COM 元件、無法處理大檔、阻塞執行緒。

方式二:WebClient 直接下載(伺服器端代碼)

using (var wc = new WebClient()) {
  wc.DownloadFile("https://localhost/a.gif", @"c:\a.gif");
}

用途:伺服器端背景作業下載外部資源,**非提供給用戶下載**。無提示、直接寫入磁碟。

方式三:標準串流下載(推薦,支援大檔、進度、斷點)

public void DownloadFile(string filePath) {
  string fileName = Path.GetFileName(filePath);
  if (!File.Exists(filePath)) { Response.StatusCode = 404; return; }

  Response.Buffer = false; // 關閉緩衝,即時串流
  Response.Clear();
  Response.ContentType = "application/octet-stream";
  Response.AddHeader("Content-Disposition", $"attachment; filename={HttpUtility.UrlEncode(fileName)}");
  Response.AddHeader("Content-Length", new FileInfo(filePath).Length.ToString());
  Response.AddHeader("Connection", "Keep-Alive");

  const int bufferSize = 1024 * 64; // 64KB
  byte[] buffer = new byte[bufferSize];
  long totalBytes = 0;

  using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
    int bytesRead;
    while ((bytesRead = fs.Read(buffer, 0, bufferSize)) > 0) {
      if (!Response.IsClientConnected) break; // 客戶端中斷
      Response.OutputStream.Write(buffer, 0, bytesRead);
      Response.Flush();
      totalBytes += bytesRead;
    }
  }
  Response.End();
}

關鍵細節

  • `Response.Buffer = false`:避免大檔案佔用伺服器記憶體
  • `FileShare.Read`:允許其他進程同時讀取
  • `Response.IsClientConnected`:偵測用戶取消下載,釋放資源
  • `HttpUtility.UrlEncode`:檔名含中文/特殊字元時避免亂碼
  • 大檔建議支援 Range 請求(HTTP 206 Partial Content)實現斷點續傳

進階:檔案下載服務介面

public interface IFileDownloadService {
  void Download(HttpResponseBase response, string virtualPath, string downloadName = null);
  bool SupportsRangeRequests { get; }
}

便於單元測試、切換儲存後端(本地、Azure Blob、AWS S3)。

copyright © 萬盛學電腦網 all rights reserved