我正在使用 HttpHandler 向用户发送文件。在所有浏览器上,至少查看/下载文件一次后,后续查看/下载的浏览器/应用程序会挂起。这是代码:
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();