如何使用MVC4 / Razor下载文件

用户1531040

我有一个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));
}

如何下载特定文件?

Dmytro

可能的解决方案-提供表单方法和控制器名称:

@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</>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章