提供檔案下載是常見需求,本文整理三種主流做法。
<%@ 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();
%>
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);
}
}
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;
}
需處理 `Range` 標頭,回傳 `206 Partial Content`,建議使用成熟庫或 ASP.NET Core 內建 `PhysicalFileResult`/`FileStreamResult`。