<%
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 元件、無法處理大檔、阻塞執行緒。
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();
}
public interface IFileDownloadService {
void Download(HttpResponseBase response, string virtualPath, string downloadName = null);
bool SupportsRangeRequests { get; }
}
便於單元測試、切換儲存後端(本地、Azure Blob、AWS S3)。