开发者

How to force download in MVC2?

I have a pdf and want to offer the user a simple "Download" link. How can this be made?

My idea is

- to compute the url to the pdf document on server side and store it in "viewmodel.PDFURL",

- add a <a href=...> to the view which calls a function.

- This function would use

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

to call this serverside method:

[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);
    R开发者_JAVA百科esponse.End();

    return null;
}

But return null; makes no sense to me, but the methode must return something, otherwise wont Visual Studio compile...

Any idea?

Thanks in Advance!


No need to use JSON, ajax, jquery or whatever. Simply:

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

And then construct a link:

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

Be extremely careful when exposing such action on your server as a hacker could always type the following address in his favorite browser:

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

and live happily to the rest of his life :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜