我有一个文件,它是完整路径(加上文件名)在这个变量中:
fileTemporary我想把那个文件下载到客户端。
我这样做:
HttpContext.Current.Response.TransmitFile(fileTemporary);但是什么都没有发生,我的意思是当我点击按钮时,这个文件就会执行,但是没有任何东西被下载到客户端。我没有在客户端的浏览器上看到任何文件。
我犯了什么错误?
发布于 2015-09-05 14:45:02
如果您使用MVC,您可以:
[HttpGet]
public virtual ActionResult GetFile(string fileTemporary)
{
// ...preparing file path... init fileTemporary.
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
var fileContent = new FileContentResult(bytes, "binary/octet-stream");
Response.AddHeader("Content-Disposition", "attachment; filename=\"YourFileName.txt\"");
return fileContent;
}如果您使用ASP.NET或任何您可以使用的方法(对不起,我的旧代码,但您可以理解方法):
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
SendFileBytesToResponse(bytes, fileName);
public static bool SendFileBytesToResponse(byte[] bytes, string sFileName)
{
if (bytes!= null)
{
string downloadName = sFileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"attachment; filename=" + downloadName + "; size=" + bytes.Length.ToString());
response.Flush();
response.BinaryWrite(bytes);
response.Flush();
response.End();
}
return true;
}无需修改您的解决方案:
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "binary/octet-stream");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName);
System.Web.HttpContext.Current.Response.TransmitFile(fileName);如果你想让浏览器正确地解释你的文件,你需要更精确地指定标题“内容类型”。请参阅内容类型列表
https://stackoverflow.com/questions/32414222
复制相似问题