我正在使用HttpHandler向用戶發送文件。在所有瀏覽器上,在查看/下載文件至少一次之後,瀏覽器/應用程序在隨後的視圖/下載中會掛起。這裏是代碼:通過HttpContext發送文件會導致瀏覽器掛起
private void TransmitFile(HttpContext context, string filePath, string downloadName, bool forceDownload)
{
if (File.Exists(filePath))
{
string fileName = System.IO.Path.GetFileName(filePath);
string extension = Path.GetExtension(filePath);
FileInfo fileInfo = new FileInfo(filePath);
// set the response info/headers
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
if (forceDownload)
{
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName.Replace(" ", "_") + extension);
context.Response.BufferOutput = false;
}
string type = "";
// set known types based on file extension
if (extension != null)
{
switch (extension.ToLower())
{
case ".tif":
case ".tiff":
type = "image/tiff";
break;
case ".jpg":
case ".jpeg":
type = "image/jpeg";
break;
case ".gif":
type = "image/gif";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
case "pdf":
type = "Application/pdf";
break;
case "png":
type = "image/png";
break;
case "bmp":
type = "image/bmp";
break;
default:
type = "application/octet-stream";
break;
}
}
context.Response.ContentType = type;
context.Response.TransmitFile(filePath);
context.Response.Flush();
}
else
{
Immersive.Diagnostics.Log.Warn("Requested file does not exist: " + filePath, this);
Immersive.Diagnostics.Log.Warn("", this);
}
}
我讀過,調用Response.Close()和Response.End()不是一個好主意?已經嘗試了兩個離開,並刪除,它仍然發生。
編輯:
似乎已的TransmitFile已知問題。更詳細的解釋可以在: http://www.improve.dk/blog/2008/03/29/response-transmitfile-close-will-kill-your-application
我刪除了TransmitFile並更改爲WriteFile,現在它完美工作。
context.Response.WriteFile(filePath);
context.Response.Flush();
context.Response.Close();
將BufferOutput更改爲true,並添加了End()。仍然沒有骰子。 – mickyjtwin 2009-05-20 04:05:50