如何从服务器下载文件到客户端?

Van*_*iza 7 asp.net-mvc download button asp.net-mvc-4

我有一个MVC项目,我希望用户能够通过单击按钮下载excel文件.我有文件的路径,我似乎无法通过谷歌找到我的答案.

我希望能够通过我的cshtml页面上的一个简单按钮来完成此操作:

<button>Button 1</button>
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?任何帮助是极大的赞赏!

Dar*_*rov 17

如果文件不在您的应用程序文件夹中,并且无法直接从客户端访问,则可以使用控制器操作将文件内容流式传输到客户端.这可以通过FileResult使用以下File方法从控制器操作返回a来实现:

public ActionResult Download()
{
    string file = @"c:\someFolder\foo.xlsx";
    string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    return File(file, contentType, Path.GetFileName(file));
}
Run Code Online (Sandbox Code Playgroud)

然后用指向此控制器操作的锚点替换您的按钮:

@Html.ActionLink("Button 1", "Download", "SomeController")
Run Code Online (Sandbox Code Playgroud)

或者使用锚点,您也可以使用html表单:

@using (Html.BeginForm("Download", "SomeController", FormMethod.Post))
{
    <button type="submit">Button 1</button>
}
Run Code Online (Sandbox Code Playgroud)

如果文件位于某些不可从应用程序的客户端文件夹访问的文件中,则App_Data可以使用该MapPath方法使用相对路径构造此文件的完整物理路径:

string file = HostingEnvironment.MapPath("~/App_Data/foo.xlsx");
Run Code Online (Sandbox Code Playgroud)