asp.net-mvc 如何从服务器下载文件到客户端?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25711271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:13:24  来源:igfitidea点击:

How to download a file to client from server?

asp.net-mvcasp.net-mvc-4buttondownload

提问by Vanquiza

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.

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

I'd like to be able to do this with a simple button I have on my cshtml page:

我希望能够使用我的 cshtml 页面上的一个简单按钮来做到这一点:

<button>Button 1</button>

How can I do this? Any help is greatly appreciated!

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

回答by Darin Dimitrov

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 FileResultfrom your controller action using the Filemethod:

如果该文件不在您的应用程序文件夹中并且无法直接从客户端访问,您可以使用控制器操作将文件内容流式传输到客户端。这可以通过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));
}

and then replace your button with an anchor pointing to this controller action:

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

@Html.ActionLink("Button 1", "Download", "SomeController")

Alternatively to using an anchor you could also use an html form:

除了使用锚点,您还可以使用 html 表单:

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

If the file is located inside some non-accessible from the client folder of your application such as App_Datayou could use the MapPathmethod to construct the full physical path to this file using a relative path:

如果文件位于应用程序的客户端文件夹中无法访问的某个位置,例如App_Data您可以使用该MapPath方法使用相对路径构造该文件的完整物理路径:

string file = HostingEnvironment.MapPath("~/App_Data/foo.xlsx");

回答by yuvan pradeep

HTML:

HTML:

<div>@Html.ActionLink("UI Text", "function_name", "Contoller_name", new { parameterName = parameter_value },null) </div>

Controller:

控制器:

public FileResult download(string filename) {
        string path = "";
        var content_type = "";
        path = Path.Combine("D:\file1", filename);

        if (filename.Contains(".pdf"))
        {
            content_type = "application/pdf";
        }
        return File(path, content_type, filename);
}