gpt4 book ai didi

asp.net-mvc-2 - 如何在MVC2中强制下载?

转载 作者:行者123 更新时间:2023-12-04 06:41:26 32 4
gpt4 key购买 nike

我有一个 pdf 文件,想为用户提供一个简单的“下载”链接。
这怎么可能?

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

$.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 不会编译...

任何的想法?

提前致谢!

最佳答案

无需使用 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

并幸福地度过余生:-)

关于asp.net-mvc-2 - 如何在MVC2中强制下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4192567/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com