Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

asp.net mvc - How to download a file to client from server?

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.

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:someFolderfoo.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:

@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_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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...