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);
    }
}

与教程和我的代码的唯一区别是我使用的是实际的服务器路径。

任何的想法??

4

2 回答 2

7

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

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

请注意,您需要知道内容类型。如果您真的不知道,您可以使用application/octet-streamwhich 使浏览器将其视为二进制文件。

于 2012-06-08T22:07:20.403 回答
3

你读过这个吗?

新更新:不再需要此自定义 ActionResult,因为 ASP.NET MVC 现在在框中包含一个。

使用 FileContentResult, http: //msdn.microsoft.com/en-us/library/system.web.mvc.filecontentresult.aspx获取数据

于 2012-06-08T22:07:00.390 回答