这是我关于 stackOverflow 的第一个问题。经过多次研究,当用户访问正确的 URL 时,我没有找到下载文件的方法。
.Net Framework 使用以下代码:
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();
Run Code Online (Sandbox Code Playgroud)
.Net core 的等价物是什么?谢谢
Ivv*_*van 11
如果您已经有控制器,请添加一个 Action,该 Action为磁盘上的文件返回PhysicalFile,或为内存中的二进制文件返回File:
[HttpGet]
public ActionResult Download(string fileName) {
var path = @"c:\FileDownload.csv";
return PhysicalFile(path, "text/plain", fileName);
}
Run Code Online (Sandbox Code Playgroud)
从项目文件夹注入IHostingEnvironment并获取 WebRootPath(wwroot 文件夹)或 ContentRootPath(根项目文件夹)的文件路径。
var fileName = "FileDownload.csv";
string contentRootPath = _hostingEnvironment.ContentRootPath;
return PhysicalFile(Path.Combine(contentRootPath, fileName);, "text/plain", fileName);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10793 次 |
| 最近记录: |