C# 如何在asp.net core 2.2上使函数从路径生成下载文件?
我从事项目使用.net core 2.2 visual studio 2017 Web API的工作 我需要制作函数下载文件 给出文件的功能路径将被下载并下载文件并返回作废 我需要使.NETCore2.2上的函数do下载文件在动作控制器中重用它C# 如何在asp.net core 2.2上使函数从路径生成下载文件?,c#,asp.net-mvc,ado.net,asp.net-core-webapi,asp.net-core-2.2,C#,Asp.net Mvc,Ado.net,Asp.net Core Webapi,Asp.net Core 2.2,我从事项目使用.net core 2.2 visual studio 2017 Web API的工作 我需要制作函数下载文件 给出文件的功能路径将被下载并下载文件并返回作废 我需要使.NETCore2.2上的函数do下载文件在动作控制器中重用它 public void DownloadOutPut(string path) { try { if (path != "") { System.IO.F
public void DownloadOutPut(string path)
{
try
{
if (path != "")
{
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename = " + file.Name + "");
Response.TransmitFile(path);
}
Response.End();
}
}
catch (Exception ex)
{
throw;
}
}
以上是在asp.net web表单上完成的,我需要执行与之类似的功能,但在.net core 2.2上
那么该怎么做呢?我假设您收到了一个映射路径,并且文件被放置在您的服务器上
public FileStreamResult DownloadFile(string path)
{
var filename = System.IO.Path.GetFileName(path);
var mimeType = "application/octet-stream";
var stream = System.IO.File.OpenRead(path);
return new FileStreamResult(stream, mimeType) { FileDownloadName = filename };
}
对于mimetype,我发现这个答案很有用。路径是什么?文件的URL?服务器或客户端上文件的路径?这是否回答了您的问题?是的解决了我的问题只有一个问题如果我需要将下载文件下载到下载文件夹并在浏览器上显示为文件,这将与Web api或客户端angular或jquery相关