c# - 创建文件有效,但是在下载该文件时,C# 中没有任何反应
问题描述
创建一个文件并上传它,我还想下载创建的文件。文件已成功创建,但是当下载该创建的文件时,我的以下代码没有任何反应。这是我的代码,当单击按钮但无法下载时调用文件。还要检查文件是否存在。它返回 true 但这不会给我任何错误,并且当此代码运行时没有任何反应。
[HttpPost]
public ActionResult DownloadGetOdds(string filename)
{
string filepath = Path.Combine(Server.MapPath("~/UploadFiles"), filename + ".json");
if (file.FileExist(filepath) == true)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename+".json");
Response.Flush();
Response.TransmitFile(Server.MapPath("~/UploadFiles/") +filename + ".json");
Response.End();
return Json(new { result = "SUCCESS" });
}
else
{
return Json(new {result = "Server Error" });
}
}
}
文件创建代码
public string CreateJsonFile(string path, string data)
{
string status = "";
try
{
using (StreamWriter file = File.CreateText(path))
{
string _data = data;
JsonSerializer serializer = new JsonSerializer();
//serialize object directly into file stream
serializer.Serialize(file, _data);
}
status = "Successfully file created";
}
catch(Exception ex)
{
status = ex.Message;
}
return status;
}
解决方案
使用 ajax 调用调用动作方法是下载文件的有点棘手的方法。以下代码帮助了我。
public void DownloadOdds(string filename)
{
string filepath = Path.Combine(Server.MapPath("~/UploadFiles"), filename + ".json");
if (file.FileExist(filepath) == true)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".json");
Response.Flush();
Response.TransmitFile(Server.MapPath("~/UploadFiles/") + filename + ".json");
Response.End();
}
}
html:
<button class="btn btn-default" id="downloadOdsbtn" onclick="DownloadFile()">Download Odds</button>
function DownloadFile() {
var file = $("#fileNameID").val();
window.location.href = '@Url.Action("DownloadOdds", "Home", new { filename = "ff" })'.replace("ff", file);
}
推荐阅读
- c - _CRT_SECURE_NO_WARNINGS 实际上是什么意思?
- c - 使用 strtok 时出现分段错误
- r - dplyr 在改变数据框时将日期转换为双精度
- php - 在 PHP 中迭代 JSON 键
- r - 在 R 中读取多个 xml 文件并合并数据时出现工作目录错误
- mysql - Docker-compose.yml for NodeJs with MySQL on AWS Elastic Beanstalk 单容器 Docker
- c# - 如果发件人是静态类或静态类中的对象,如何在 MessagingCenter.Send 中指定发件人?
- c# - ASP.NET web api 2 截断 json 响应
- python - 有没有一种优雅的方法可以结合 Python vars() 和 filter() 函数来显示变量子集的值?
- reactjs - 注册用户时 React props.auth.user 未定义