如何在MVC2中强制下载?

时间:2010-11-16 09:16:03

标签: asp.net-mvc-2

我有一个pdf,并希望为用户提供一个简单的“下载”链接。 怎么能这样做?

我的想法是 - 计算服务器端pdf文档的URL并将其存储在“viewmodel.PDFURL”中,
- 在调用函数的视图中添加<a href=...> - 此功能将使用

$.post("ForcePDFDownload", { PDFURL: <%: Model.PDFURL %> } );

调用此服务器端方法:

[HttpPost]
public JsonResult ForcePDFDownload(string PDFURL)
{
    string path = Path.GetFullPath(PDFURL);
    string filename = Path.GetFileName(PDFURL);
    Response.AppendHeader("content-disposition", "attachment; filename=" + filename);
    Response.ContentType = "application/pdf";
    Response.WriteFile(path);
    Response.End();

    return null;
}

但是return null;对我没有意义,但是这个方法必须返回一些东西,否则Visual Studio不会编译......

有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:3)

无需使用JSON,ajax,jquery等等。简单地:

public ActionResult ForcePDFDownload(string PDFURL)
{
    string path = Path.GetFullPath(PDFURL);
    string filename = Path.GetFileName(PDFURL);
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
    return File(path, "application/pdf");
}

然后构建一个链接:

<%: Html.ActionLink("Download PDF", "ForcePDFDownload", new { PDFURL = Model.PDFURL }) %>

在服务器上公开此类操作时要非常小心,因为黑客总是可以在他最喜欢的浏览器中输入以下地址:

http://foo.com/somecontroller/forcepdfdownload/?pdfurl=c%3A%5Cmycreditcardnumbers.txt

并幸福地度过他的余生: - )