Response.TransmitFile发送零字节文件

时间:2011-02-21 03:58:32

标签: c# asp.net download httphandler

我正在尝试通过自定义处理程序下载zip文件。该文件作为零字节zip文件下载。但原始文件不是零字节zip文件。 代码是ProcessRequest(HttpContext context)

            String file = Directory.GetFiles(cachePath).FirstOrDefault();
            String filename = Path.GetFileName(file);

            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            context.Response.ContentType = "application/zip";
            //byte[] bytes = File.ReadAllBytes(file);
            //context.Response.BinaryWrite(bytes);
            context.Response.TransmitFile(file);
            context.Response.Flush();

2 个答案:

答案 0 :(得分:0)

也许你需要Content-Length

context.Response.AddHeader("Content-Length", new FileInfo(file).Length.ToString());

或者您可能缺少ContentType

context.Response.ContentType = "application/octet-stream";

作为最后的手段,它可能与缓存有关。

context.Response.Cache.SetNoStore();

答案 1 :(得分:0)

该代码看起来很准确。我使用几乎相同的代码片段在我的网站上执行文件下载。我唯一看不到的是你从中检索文件的路径。您可能需要执行HostingEnvironment.ApplicationPhysicalPath以获取文件的实际路径。