【问题标题】:Generic handler file download does not start通用处理程序文件下载未开始
【发布时间】: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;
}

我正在单步执行代码,没有出现任何问题,但浏览器中也没有显示文件下载弹出窗口。

你看出什么不对了吗?

【问题讨论】:

标签: c# httpcontext ashx generic-handler


【解决方案1】:

我相信你遇到的问题是你打电话给HttpContext.Current。由于您使用了通用处理程序文件,我相信您会想要使用传递给您的方法签名的context 参数。一个例子是:

public void ProcessRequest (HttpContext context)
{
     // Build Document and Zip:
     BuildAndZipDocument(); 

     // Context:
     context.Response.ContentType = "application/zip";
     context.Response.AddHeader("content-disposition", "filename="Commodity.zip");
     zip.Save(context.Response.OutputStream);

     // Close:
     context.Response.End();
}

我相信如果您使用context,而不是HttpContext.Current,它将解决您的问题。

【讨论】:

  • 不,切换上下文时输出仍然相同。您还介绍了 BuildAndZipDocument 方法,这是为什么呢?谢谢
  • 这来自我拥有的物理工作代码,这只是执行任务的示例方法。
  • BuildAndZipDocument 方法中的内容,您能分享一下吗?谢谢
  • 这对您解决问题有什么好处?这是在构建一个 Excel 文档,当然我还有另一个可以构建 Excel 并填充 pdf 目录的文档。
  • 没关系,感谢您的努力,但我仍然没有回答我的问题。
【解决方案2】:

切勿在 ZIP 文件的 Content-Type 标头中使用“application/zip”。绝不!已确认的错误在 IE6 中,它会损坏下载。

如果您希望二进制文件在过去和现在的大多数浏览器中具有最通用的行为,请始终使用“application/octet-stream”,就像您在其他任何地方看到的一样!

header('Content-Type: application/octet-stream');

假设您关心,这克服了 IE6 错误。尽管如此,从 application/octet-stream 切换到 application/zip 并没有取得任何成果,因此您不妨停止在那个上浪费时间并保留它 application/octet-stream。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    相关资源
    最近更新 更多