【问题标题】:How to download file with MVC4/Razor如何使用 MVC4/Razor 下载文件
【发布时间】:2014-09-01 22:35:00
【问题描述】:

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

如何下​​载特定文件?

【问题讨论】:

标签: c# asp.net-mvc-4 razor


【解决方案1】:

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

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

【讨论】:

  • 我的问题是 APP_DATA 文件夹是保留名称。我无法从该文件夹中获取文件。所以我不得不将我的文件移动到另一个文件夹。
  • 我肯定会使用 ActionLink 方法,因为这允许您使用 ActionFilter 来授权/验证用户是否能够下载文件。通常,如果用户无权下载链接,甚至不应该显示链接,但如果 url 是由第三方以某种方式获得的,那么您仍然可以控制安全性。
【解决方案2】:

DownloadFile Action 签名从:

 public ActionResult DownloadFile()

收件人:

 public FileResult DownloadFile()

另外我觉得文件路径的UrlEncode是多余的,改成:

return File(sDocument, "application/pdf", sDocument);

并确保这条路径确实存在。

【讨论】:

  • 文件仍未下载。
  • 我不知道。我希望下载箭头下的文件(firefox)。该网站显示没有错误。看起来系统读取了一些内容,然后他完成了。
  • 这个解决方案对我有用(在 MVC 4 中并在剃刀视图中使用 Html.ActionLink 来构建下载 URL),所以我更喜欢它而不是公认的答案:它不仅看起来像最简单的和最干净的解决方案,但也像我想象的 MVC/Razor 设计者在设计 API 时所想的那样。
猜你喜欢
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多