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

ASP.NET 網絡硬盤實作 (二):檔案下載與線上預覽

     編輯:關於ASP.NET

下載實作:Response.TransmitFile / BinaryWrite

// 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、部份影音) 會直接在頁面/新分頁顯示。

統一處理:Download.ashx 處理下載與預覽

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;
}

前端連結:


下載

預覽

大檔案支援:Range Requests (斷點續傳)

`TransmitFile` 不支援 Range。需自行實作:

  • 檢查 `Request.Headers["Range"]` (格式: `bytes=0-1023`)。
  • 回應 `206 Partial Content`、`Content-Range: bytes 0-1023/20000`、`Accept-Ranges: bytes`。
  • 使用 `FileStream` `Seek` + `Read` + `OutputStream.Write` 分塊輸出。

建議:大檔案下載功能直接使用 **IIS 靜態檔案服務 + URL 授權** 或 **Azure Blob SAS Token**,避免自行實作複雜邏輯。

預覽增強:Office/PDF 線上閱讀器

  • Microsoft Office Online Viewer: `https://view.officeapps.live.com/op/view.aspx?src={檔案公開URL}`
  • Google Docs Viewer: `https://docs.google.com/gview?url={檔案公開URL}&embedded=true`
  • PDF.js (Mozilla) 自架:純 JS 渲染 PDF,無外部依賴。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved