How to download a file with asp.net Core ?
11,510
If you already have a controller, add an Action that return PhysicalFile for file on your disc or File for binary file in memeory:
[HttpGet]
public ActionResult Download(string fileName) {
var path = @"c:\FileDownload.csv";
return PhysicalFile(path, "text/plain", fileName);
}
To file path from project folder inject IHostingEnvironment and get WebRootPath (wwroot folder) or ContentRootPath (root project folder).
var fileName = "FileDownload.csv";
string contentRootPath = _hostingEnvironment.ContentRootPath;
return PhysicalFile(Path.Combine(contentRootPath, fileName);, "text/plain", fileName);
Related videos on Youtube
Author by
Boursomaster
Updated on September 14, 2022Comments
-
Boursomaster over 1 year
This is my first question on stackOverflow. After many research i don't find a way to download a file when the user go on the right URL.
With .Net Framework is used the following code :
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile(Server.MapPath("FileDownload.csv")); response.Flush(); response.End();
What is the equivalent with .Net core ? Thanks
-
Boursomaster over 5 yearsI'm using razor pages, so there is no controler.
-
Ivvan over 5 yearsThe idea still the same, almost no differences, just follow razor pages convention - no attribute on method and use handler to call the method, like 'OnGetFileDownload'. Still you can pass the parameter and you have access to the helper method
PhysicalFile
.