萬盛學電腦網

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

ASP.NET 大檔案下載完整實作與效能優化

大檔下載核心原則

  1. 分塊讀取/寫入:避免一次載入整個檔案至記憶體導致 OOM。
  2. 正確 Content-Type:依副檔名對應 MIME,參考 OSChina 對照表。
  3. 每次寫入後 Flush:`Response.Flush()` 立即推送至客戶端。
  4. 檢查 Client 連線:`Response.IsClientConnected` 偵測斷線,及早釋放資源。
  5. 結束請求:`Response.End()` 確保執行緒終止。

完整程式碼 (WebForms)

public partial class DownloadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.IO.Stream iStream = null;
        const int bufferSize = 10000; // 10KB 緩衝區
        byte[] buffer = new byte[bufferSize];
        long dataToRead;

        try
        {
            string filepath = Server.MapPath("~/Files/TextFile1.txt");
            string filename = Path.GetFileName(filepath);

            iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
            dataToRead = iStream.Length;

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "text/plain"; // 依實際檔案類型調整
            Response.AddHeader("Content-Length", dataToRead.ToString());
            Response.AddHeader("Content-Disposition", $"attachment; filename={filename}");

            while (dataToRead > 0)
            {
                if (Response.IsClientConnected)
                {
                    int length = iStream.Read(buffer, 0, bufferSize);
                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();
                    buffer = new byte[bufferSize]; // 重新分配避免殘留資料
                    dataToRead -= length;
                }
                else
                {
                    dataToRead = -1; // 客戶端斷線,跳出迴圈
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error: " + ex.Message);
        }
        finally
        {
            iStream?.Close();
            Response.End();
        }
    }
}

MVC 版本 (Controller Action)

public FileResult Download(string path)
{
    string fullPath = Server.MapPath(path);
    if (!System.IO.File.Exists(fullPath)) return HttpNotFound();

    string mime = MimeMapping.GetMimeMapping(fullPath); // .NET 4.5+
    return File(fullPath, mime, Path.GetFileName(fullPath));
    // FileResult 內建支援分塊傳輸、Range 請求 (斷點續傳)
}

進階:支援斷點續傳 (Range Header)

public ActionResult DownloadRange(string path)
{
    var filePath = Server.MapPath(path);
    var fileInfo = new FileInfo(filePath);
    long fileSize = fileInfo.Length;
    long start = 0, end = fileSize - 1;

    var rangeHeader = Request.Headers["Range"];
    if (!string.IsNullOrEmpty(rangeHeader))
    {
        var parts = rangeHeader.Replace("bytes=", "").Split('-');
        start = long.Parse(parts[0]);
        if (parts.Length > 1 && !string.IsNullOrEmpty(parts[1]))
            end = long.Parse(parts[1]);
    }

    long contentLength = end - start + 1;
    Response.StatusCode = 206; // Partial Content
    Response.AddHeader("Content-Range", $"bytes {start}-{end}/{fileSize}");
    Response.AddHeader("Accept-Ranges", "bytes");
    Response.ContentType = MimeMapping.GetMimeMapping(filePath);
    Response.AddHeader("Content-Length", contentLength.ToString());
    Response.AddHeader("Content-Disposition", $"attachment; filename={fileInfo.Name}");

    using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        fs.Seek(start, SeekOrigin.Begin);
        byte[] buffer = new byte[10240];
        long remaining = contentLength;
        while (remaining > 0 && Response.IsClientConnected)
        {
            int read = fs.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining));
            Response.OutputStream.Write(buffer, 0, read);
            Response.Flush();
            remaining -= read;
        }
    }
    Response.End();
    return new EmptyResult();
}

效能調優建議

  • 緩衝區 64KB-256KB 平衡記憶體與系統呼叫次數。
  • 啟用 IIS 動態壓縮 (僅限文字型檔案),二進位檔案 (zip、exe、mp4) 勿壓縮。
  • 大量並發下載考慮 CDN、Blob Storage (Azure Blob、AWS S3) 簽名 URL 直傳,卸載 Web Server 頻寬。
  • 監控 `ASP.NET Applications\Request Execution Time`、`Process\Private Bytes`。<
copyright © 萬盛學電腦網 all rights reserved