ASP.NET MVC 文件下载

3
我正在跟随一个教程从服务器下载文件。但遇到了一些问题。我一定是犯了一些愚蠢的错误..!!
这是我正在使用的链接: http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx 要求是:用户单击链接,站点将带他们进入详细页面。在该详细页面上,将有一个下载链接。当用户单击该下载链接时,将下载文件。
问题是,当我单击下载链接时,它不会下载原始文件。而是下载一个HTML文件。如果我单击HTML文件,它会显示垃圾。
这是我的代码:
操作:
public ActionResult Download(string path,string name)
    {
        return new DownloadResult { VirtualPath = path, FileDownloadName = name };
    }

下载结果类

public class DownloadResult : ActionResult
{

    public DownloadResult()
    {
    }

    public DownloadResult(string virtualPath)
    {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath
    {
        get;
        set;
    }

    public string FileDownloadName
    {
        get;
        set;
    }

    public override void ExecuteResult(ControllerContext context) 
    {
        if (!String.IsNullOrEmpty(FileDownloadName)) 
        {
            context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + this.FileDownloadName);
        }

        string filePath = this.VirtualPath; //context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}

唯一的区别是我使用实际服务器路径,与教程不同。 有什么想法吗?
2个回答

7

如果您需要向客户端发送文件并且知道路径,请使用FilePathResult

public ActionResult Download(string path, string name)
{
    return new FilePathResult(path, contentType) {
         FileDownloadName = name
    }
}

请注意您需要了解内容类型。如果您确实不知道,可以使用 application/octet-stream,它会使浏览器将其视为二进制文件。

3

嘿,谢谢。我没注意到那个。 - Reza.Hoque

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