我有一个 MVC 项目,我希望用户能够通过单击按钮下载一个 excel 文件。我有文件的路径,但我似乎无法通过谷歌找到我的答案。
我希望能够使用我的 cshtml 页面上的一个简单按钮来做到这一点:
<button>Button 1</button>
我怎样才能做到这一点?任何帮助是极大的赞赏!
最佳答案
如果该文件不在您的应用程序文件夹中并且无法直接从客户端访问,您可以使用 Controller 操作将文件内容流式传输到客户端。这可以通过返回 FileResult
来实现。从您的 Controller 操作使用 File
方法:
public ActionResult Download()
{
string file = @"c:\someFolder\foo.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(file, contentType, Path.GetFileName(file));
}
然后将您的按钮替换为指向此 Controller 操作的 anchor :
@Html.ActionLink("Button 1", "Download", "SomeController")
除了使用 anchor ,您还可以使用 html 表单:
@using (Html.BeginForm("Download", "SomeController", FormMethod.Post))
{
<button type="submit">Button 1</button>
}
如果文件位于应用程序的客户端文件夹中无法访问的某个文件夹中,例如
App_Data
您可以使用 MapPath
使用相对路径构造此文件的完整物理路径的方法:string file = HostingEnvironment.MapPath("~/App_Data/foo.xlsx");
关于asp.net-mvc - 如何从服务器下载文件到客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711271/