gpt4 book ai didi

c# - 如何使用 MVC4/Razor 下载文件

转载 作者:太空狗 更新时间:2023-10-30 00:01:24 25 4
gpt4 key购买 nike

我有一个 MVC 应用程序。我想下载一个pdf。

这是我的部分观点:

<p>
<span class="label">Information:</span>
@using (Html.BeginForm("DownloadFile")) { <input type="submit" value="Download"/> }
</p>

这是我 Controller 的一部分:

private string FDir_AppData = "~/App_Data/";

public ActionResult DownloadFile()
{
var sDocument = Server.MapPath(FDir_AppData + "MyFile.pdf");

if (!sDocument.StartsWith(FDir_AppData))
{
// Ensure that we are serving file only inside the App_Data folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}

if (!System.IO.File.Exists(sDocument))
{
return HttpNotFound();
}

return File(sDocument, "application/pdf", Server.UrlEncode(sDocument));
}

如何下​​载特定文件?

最佳答案

可能的解决方案——提供表单方法和 Controller 名称:

@using (Html.BeginForm("DownloadFile", "Controller", FormMethod.Get))
{ <input type="submit" value="Download" /> }

尝试使用操作链接而不是表单:

@Html.ActionLink("Download", "DownloadFile", "Controller")

尝试提供文件的直接 url:

<a href="~/App_Data/MyFile.pdf">Download</>

出于安全原因,这不是最佳做法,但您仍然可以尝试...此外,您可以将文件位置包装到一些 @Html 辅助方法中:

public static class HtmlExtensions {
private const string FDir_AppData = "~/App_Data/";

public static MvcHtmlString File(this HtmlHelper helper, string name){
return MvcHtmlString.Create(Path.Combine(FDir_AppData, name));
}
}

在 View 中:

<a href="@Html.File("MyFile.pdf")">Download</>

关于c# - 如何使用 MVC4/Razor 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25613617/

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