从服务器下载ASP.NET文件

时间:2015-06-16 10:15:16

标签: asp.net iis infragistics

我想从服务器下载文件到客户端。 我在互联网上找到的解决方案都没有,它们都将文件写入服务器,但从不在客户端的浏览器上弹出下载窗口。 我不知道它是ASP.NET问题还是IIS。

这是我的代码:

Workbook wb = getExcel();
string pathDownload = HttpContext.Current.Server.MapPath("~/Content/DOCUMENTS/temp/Excel.xls");

BIFF8Writer.WriteWorkbookToFile(wb, pathDownload);
byte[] fileContent = System.IO.File.ReadAllBytes(pathDownload);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=Excel.xls");
HttpContext.Current.Response.BinaryWrite(fileContent);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

1 个答案:

答案 0 :(得分:0)

由于WriteWorkbookToFile已将有问题的文件写入文件系统,因此最好直接从那里使用它而不是将其加载到内存中,然后执行BinaryWrite。

删除该行:

byte[] fileContent = System.IO.File.ReadAllBytes(pathDownload);

然后替换行:

HttpContext.Current.Response.BinaryWrite(fileContent);

使用:

HttpContext.Current.Response.TransmitFile(pathDownload);