首页 > 解决方案 > 创建文件有效,但是在下载该文件时,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;
        }

标签: c#jsondownloadfilestream

解决方案


使用 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);
    }

推荐阅读