【发布时间】:2015-07-07 22:17:03
【问题描述】:
我正在尝试从服务器开始下载文件,现在只是为存在的文件添加了一些硬编码值,但由于某种原因,下载没有开始并且没有引发错误。
这是我的代码:
public void ProcessRequest(HttpContext context)
{
string destPath = context.Server.MapPath("~/Attachments/cover.txt");
// Check to see if file exist
FileInfo fi = new FileInfo(destPath);
if (fi.Exists)
{
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + "cover.txt");
HttpContext.Current.Response.BinaryWrite(ReadByteArryFromFile(destPath));
HttpContext.Current.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
private byte[] ReadByteArryFromFile(string destPath)
{
byte[] buff = null;
FileStream fs = new FileStream(destPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(destPath).Length;
buff = br.ReadBytes((int)numBytes);
return buff;
}
我正在单步执行代码,没有出现任何问题,但浏览器中也没有显示文件下载弹出窗口。
你看出什么不对了吗?
【问题讨论】:
-
您是否检查了标题并确保确实填充了
byte[]? -
我也尝试过使用 pdf,因为您可以看到实际 pdf 的内容写在响应选项卡中,但该文档未显示供下载i.gyazo.com/c4038962e8a385257c8eb8cf257fc9a7.png
标签: c# httpcontext ashx generic-handler