[英]execute FileContentResult without using Return
How can i download csv file without ending The Action by using return Command?如何使用 return 命令在不结束动作的情况下下载 csv 文件?
I want to have an action that can download a csv file and continue with action logic.我想要一个可以下载 csv 文件并继续执行操作逻辑的操作。 is it possible to initiate a request without actually end the action and return back from the controller?是否可以在不实际结束操作的情况下发起请求并从 controller 返回? something like that:类似的东西:
public IActionResult AddOrdersExtension(OrderVM orderVM)
{
if (ModelState.IsValid)
{
StringBuilder sb = new StringBuilder();
//Header
sb.Append("Product,Empty,Name,Address1,Address2,City,State,zip,Country,Phone,Quantity,Weight");
FileContentResult fr = File(Encoding.ASCII.GetBytes(sb.ToString()), "text/csv",
"Error_log.csv");
//
//execute csv download
//
// continue with function
return View(orderVM.Orders); // return from action when logic is done
}//end function
From your codes, the following is an in-memory operation:从您的代码中,以下是内存操作:
FileContentResult fr = File(Encoding.ASCII.GetBytes(sb.ToString()), "text/csv",
"Error_log.csv");
Do download the file from the server again you need to store the file.请再次从服务器下载文件,您需要存储该文件。 Not sure why you want to download the file here, But if you want you can save the file to a temporary folder: download and then remove the file like this:不确定为什么要在此处下载文件,但如果需要,可以将文件保存到临时文件夹:下载然后删除文件,如下所示:
FileContentResult fr = File(Encoding.ASCII.GetBytes(sb.ToString()), "text/csv", "Error_log.csv");
//For concurrent access use dynamic name file names //对于并发访问使用动态名称文件名
//Save to disk //保存到磁盘
File.WriteAllBytes( "~/tmp/Error_log.csv", ((FileContentResult)fr).FileContents);
//Download //下载
string remoteUri = "http://www.yourdomain.com/tmp/";
string fileName = "Error_log.csv_downloaded", myStringWebResource = null;
// Create a new WebClient instance and download the file // 创建一个新的 WebClient 实例并下载文件
using (WebClient myWebClient = new WebClient())
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
}
//Delete both the files //删除两个文件
var fullPath = Server.MapPath("~/tmp/Error_log.csv");
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}
fullPath = Server.MapPath("~/tmp/Error_log.csv_downloaded");
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}
There might be some syntax errors and reference libraries to be added.可能有一些语法错误和要添加的参考库。 But I hope you get the solution you are looking for.但我希望你能得到你正在寻找的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.