用 XMLHTTP 下載檔案的做法和以往一樣:先加入參考,然後在程式碼中呼叫。
在專案中加入 COM 參考:Microsoft XML 3.0,然後在程式碼開頭引入命名空間:
using MSXML2;
private void Page_Load(object sender, System.EventArgs e)
{
string url = "/School/UploadFiles/20110423153946171.gif";
string fileName = url.Substring(url.LastIndexOf("/") + 1);
string basePath = Request.PhysicalApplicationPath;
if (!basePath.EndsWith("/")) basePath += "/";
MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
_xmlhttp.open("GET", url, false, null, null);
_xmlhttp.send("");
if (_xmlhttp.readyState == 4)
{
if (System.IO.File.Exists(basePath + fileName))
System.IO.File.Delete(basePath + fileName);
System.IO.FileStream fs =
new System.IO.FileStream(basePath + fileName, System.IO.FileMode.CreateNew);
System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs);
w.Write((byte[])_xmlhttp.responseBody);
w.Close();
fs.Close();
Response.Write("檔案已取得。<br><a href='" + Request.ApplicationPath + fileName + "' target='_blank'>");
Response.Write("檢視" + fileName + "</a>");
}
else
{
Response.Write(_xmlhttp.statusText);
}
Response.End();
}
CreateNew 模式建立新檔。BinaryWriter 把 responseBody(位元組陣列)寫入。responseBody 一定要轉成 byte[]。XMLHTTP 的二進位回應是位元組陣列,直接寫入會失敗;用 responseText 則會因編碼轉換而破壞檔案內容。
檔名來自網址就有風險。範例直接從 URL 字串擷取檔名並寫入實體路徑,如果這個 URL 含有外部輸入,就可能被植入 .. 造成路徑穿越,寫到不該寫的位置。實務上應改用 Path.GetFileName() 取得純檔名,並驗證最終完整路徑確實位於允許的目錄之下。
同步呼叫會佔住執行緒。這段程式在 Page_Load 中以同步方式抓取整個檔案,抓取期間該請求的執行緒會被完全佔用。下載大檔或高併如下載時,這會迅速耗盡 IIS 的工作執行緒。若只是偶爾抓小檔還好,否則應改用非同步模式或改用 HttpWebRequest 搭配串流寫檔。
把檔案寫進站台目錄要謹慎。讓使用者觸發的請求直接在你的 Web 可存取目錄下產生檔案,等於開了一個寫入面。建議存到 Web 根目錄之外,或至少限制副檔名白名單,並確認該目錄不允許執行。