我有一个 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/