繁体   English   中英

ASP.NET从服务器下载文件

[英]ASP.NET download file from server

我想将文件从服务器下载到客户端。 我在Internet上找到的两种解决方案都没有,它们都将文件写入服务器,但从未在客户端浏览器上弹出下载窗口。 我不知道这是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();

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

删除行:

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

然后替换该行:

HttpContext.Current.Response.BinaryWrite(fileContent);

与:

HttpContext.Current.Response.TransmitFile(pathDownload);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM