在ASP.NET中使用HttpContext.Current.Response.TransmitFile下载文件

3
public void Downloadfile(string sFileName, string sFilePath)
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
    String Header = "Attachment; Filename=" + sFileName;
    HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
    HttpContext.Current.Response.AppendHeader("Cache-Control", "no-cache");
    System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
    HttpContext.Current.Response.TransmitFile(Dfile.FullName);
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

我有一个下载按钮,点击后会返回调用并下载相应的文件,但有时文件返回的是detailt.aspx文件。我不明白发生了什么。

我需要帮助。非常感谢。

1个回答

7
这对我来说一直没有问题。
public void Downloadfile(string sFileName, string sFilePath)
{
    var file = new System.IO.FileInfo(sFilePath);

    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + sFileName);
    Response.AddHeader("Content-Length", file.Length.ToString(CultureInfo.InvariantCulture));
    Response.ContentType = "application/octet-stream";
    Response.WriteFile(file.FullName);
    Response.End();
}

1
谢谢David Negron的回复。 但是当我使用Response.End()时,会抛出异常: exception = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} 我不理解这个错误。你能解释一下吗? - user2828601
你是否试图在调用Downloadfile之后执行其他代码?我问这个问题是因为我通常从HttpHandler中调用此类型的代码。有关此示例,请参见以下文章:http://geekswithblogs.net/hmloo/archive/2012/03/07/how-to-download-files-using-a-generic-handler.aspx - David Negron
我这里也遇到了同样的问题,按照这里的回答,在所有响应命令(如内存流读取)之后加上response.clear和其他response命令可以解决问题,否则你将不会得到任何异常回显。我的情况是文件系统权限问题,因为IIS运行在与我的Visual Studio不同的用户上,并且异常被消耗了,网页输出了一个HTML输出(可能是活动页面的HTML,我没有去读它)。 - Nick Andriopoulos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接