我有一个MVC应用程序。我想下载pdf。
这是我观点的一部分:
<p>
<span class="label">Information:</span>
@using (Html.BeginForm("DownloadFile")) { <input type="submit" value="Download"/> }
</p>
这是我的控制器的一部分:
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));
}
如何下载特定文件?
答案 0 :(得分:9)
可能的解决方案 - 提供表单方法和控制器名称:
@using (Html.BeginForm("DownloadFile", "Controller", FormMethod.Get))
{ <input type="submit" value="Download" /> }
或尝试使用操作链接而不是表单:
@Html.ActionLink("Download", "DownloadFile", "Controller")
或尝试为文件提供直接网址:
<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));
}
}
在视图中:
<a href="@Html.File("MyFile.pdf")">Download</>
答案 1 :(得分:7)
更改DownloadFile
操作签名:
public ActionResult DownloadFile()
要:
public FileResult DownloadFile()
此外,我认为文件路径的UrlEncode
是多余的,请将其更改为:
return File(sDocument, "application/pdf", sDocument);
并确保此路径确实存在。