// Download.aspx?file=encoded_full_path
protected void Page_Load(object sender, EventArgs e)
{
string encodedPath = Request.QueryString["file"];
if (string.IsNullOrEmpty(encodedPath)) { Response.StatusCode = 400; return; }
string fullPath = Server.UrlDecode(encodedPath);
FileInfo file = new FileInfo(fullPath);
// 安全性檢查 (同上篇 IsPathSafe)
if (!file.Exists || !IsPathSafe(fullPath, RootPath)) { Response.StatusCode = 404; return; }
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false; // 串流模式
Response.ContentType = GetMimeType(file.Extension);
Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(file.Name, Encoding.UTF8)}\"");
Response.AddHeader("Content-Length", file.Length.ToString());
Response.TransmitFile(fullPath); // IIS 內核傳輸,效能最佳、不佔用 Managed 記憶體
Response.End();
}
string GetMimeType(string ext)
{
switch (ext.ToLower())
{
case ".pdf": return "application/pdf";
case ".jpg": case ".jpeg": return "image/jpeg";
case ".png": return "image/png";
case ".gif": return "image/gif";
case ".txt": return "text/plain";
case ".zip": return "application/zip";
default: return "application/octet-stream";
}
}
將 `Content-Disposition` 從 `attachment` 改為 `inline`:
Response.AddHeader("Content-Disposition", $"inline; filename=\"{HttpUtility.UrlEncode(file.Name, Encoding.UTF8)}\"");
瀏覽器支援的類型 (PDF、圖片、文字、HTML、部份影音) 會直接在頁面/新分頁顯示。
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string fileParam = context.Request.QueryString["file"];
bool preview = context.Request.QueryString["preview"] == "1";
// ... 安全性檢查、FileInfo ...
context.Response.ContentType = mimeType;
context.Response.AddHeader("Content-Disposition",
$"{ (preview ? "inline" : "attachment") }; filename=\"{HttpUtility.UrlEncode(file.Name, Encoding.UTF8)}\"");
context.Response.AddHeader("Content-Length", file.Length.ToString());
context.Response.TransmitFile(file.FullName);
}
public bool IsReusable => false;
}
前端連結:
下載
預覽
`TransmitFile` 不支援 Range。需自行實作:
建議:大檔案下載功能直接使用 **IIS 靜態檔案服務 + URL 授權** 或 **Azure Blob SAS Token**,避免自行實作複雜邏輯。