如何从服务器下载文件到客户端? [英] How to download a file to client from server?
问题描述
我有一个MVC项目,我希望用户单击一下按钮就可以下载Excel文件.我有文件的路径,但似乎无法通过Google找到答案.
I have an MVC project where I'd like the user to be able to download a an excel file with a click of a button. I have the path for the file, and I can't seem to find my answer through google.
我希望能够通过我在cshtml页面上使用的简单按钮来做到这一点:
I'd like to be able to do this with a simple button I have on my cshtml page:
<button>Button 1</button>
我该怎么做?任何帮助,我们将不胜感激!
How can I do this? Any help is greatly appreciated!
推荐答案
如果该文件不在您的应用程序文件夹中,并且不能直接从客户端访问,则可以执行控制器操作,该操作会将文件内容流式传输到客户端.这可以通过使用 File
方法:
If the file is not located inside your application folders and not accessible directly from the client you could have a controller action that will stream the file contents to the client. This could be achieved by returning a FileResult
from your controller action using the File
method:
public ActionResult Download()
{
string file = @"c:\someFolder\foo.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(file, contentType, Path.GetFileName(file));
}
,然后用指向此控制器操作的锚点替换您的按钮:
and then replace your button with an anchor pointing to this controller action:
@Html.ActionLink("Button 1", "Download", "SomeController")
或者使用锚,也可以使用html表单:
Alternatively to using an anchor you could also use an html form:
@using (Html.BeginForm("Download", "SomeController", FormMethod.Post))
{
<button type="submit">Button 1</button>
}
如果文件位于应用程序的客户端文件夹(例如App_Data
)中某些不可访问的文件内,则可以使用
If the file is located inside some non-accessible from the client folder of your application such as App_Data
you could use the MapPath
method to construct the full physical path to this file using a relative path:
string file = HostingEnvironment.MapPath("~/App_Data/foo.xlsx");
这篇关于如何从服务器下载文件到客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!