如何在ASP.NET Core中下载.json文件

发布于 2025-02-13 11:56:29 字数 1139 浏览 0 评论 0原文

我在控制器中的下载方法是

public FileResult GenerateJSON()
{
    string filename = "aa.json";
    string filepath = VariableDeclarations.wwwPath + @"\Downloads\" + filename;
    string filedata = System.IO.File.ReadAllText(filepath);
    string contentType = GetContentType(filepath);

    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = filename,
        Inline = true
            
    };

    HttpContext.Response.Headers.Add("Content-Disposition",$"attachment;filename=aa.json");

    return File(filedata, "application/json", filename);
}

且视图代码在按钮上单击

function OnClickbtn() {
   

        $.ajax({
        type: "POST",
        url: vGenerateUrl,
        data: { },
        success: function(s) {
            DevExpress.ui.notify({ message: "xyz Generated", width: 1300 }, vSuccessMsgType, 3000);
        },
        error: function(result) {
            onAjaxError(result);
        }
        });
}

按钮单击我的视图,从我的视图中生成.json文件,我需要下载该.JSON文件,应在浏览器中下载,但是在多次努力从ActionResult,ContentResult进行更改之后fileResult我仍然无法在浏览器中下载文件。

我需要在上面的代码中进行哪些更改才能在浏览器中下载.json文件?

My Download Method in Controller is

public FileResult GenerateJSON()
{
    string filename = "aa.json";
    string filepath = VariableDeclarations.wwwPath + @"\Downloads\" + filename;
    string filedata = System.IO.File.ReadAllText(filepath);
    string contentType = GetContentType(filepath);

    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = filename,
        Inline = true
            
    };

    HttpContext.Response.Headers.Add("Content-Disposition",
quot;attachment;filename=aa.json");

    return File(filedata, "application/json", filename);
}

and View Code is On button Click

function OnClickbtn() {
   

        $.ajax({
        type: "POST",
        url: vGenerateUrl,
        data: { },
        success: function(s) {
            DevExpress.ui.notify({ message: "xyz Generated", width: 1300 }, vSuccessMsgType, 3000);
        },
        error: function(result) {
            onAjaxError(result);
        }
        });
}

On Button click from my view a .json file is generated and i need to download that .json file should be downloaded in browser but after multiple efforts for changing it from actionresult, contentresult and fileresult I am still not able to download a file in my browser.

what changes do I need to make in the above code to download .json file in browser?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

永言不败 2025-02-20 11:56:29

以下是浏览器中的关于下载.json文件的演示,您可以参考它。

在视图中:

<input type="button" value="Download Json" onclick="DownloadJson()" />
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        function DownloadJson() {
            var studentList = [
                { "Name": "John", "score": "30" },
                { "Name": "Rozi", "score": "40" },
                { "Name": "Peter", "score": "50" },
                { "Name": "Finch", "score": "60" },
                { "Name": "Ravi", "score": "70" }
            ];
            //Convert JSON Array to string.
            var json = JSON.stringify(studentList);
            var blob = new Blob([json]);
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "studentList.json";
            link.click();
        }
    </script>

结果:

”在此处输入图像描述”

public FileContentResult DownloadMission()
        {
            Mission toDownload = new Mission { Id = 1, name = "test" };
            string jsonString = JsonSerializer.Serialize(toDownload);
            var fileName = "test.json";
            var mimeType = "text/plain";
            var fileBytes = Encoding.ASCII.GetBytes(jsonString);
            return new FileContentResult(fileBytes, mimeType)
            {
                FileDownloadName = fileName
            };
        }

任务

  public class Mission
    {
        public int Id { get; set; }
        public string name { get; set; }
    }

结果:

Below is a demo about download .json file in browser, you can refer to it.

in the view:

<input type="button" value="Download Json" onclick="DownloadJson()" />
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        function DownloadJson() {
            var studentList = [
                { "Name": "John", "score": "30" },
                { "Name": "Rozi", "score": "40" },
                { "Name": "Peter", "score": "50" },
                { "Name": "Finch", "score": "60" },
                { "Name": "Ravi", "score": "70" }
            ];
            //Convert JSON Array to string.
            var json = JSON.stringify(studentList);
            var blob = new Blob([json]);
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "studentList.json";
            link.click();
        }
    </script>

result:

enter image description here

Or

public FileContentResult DownloadMission()
        {
            Mission toDownload = new Mission { Id = 1, name = "test" };
            string jsonString = JsonSerializer.Serialize(toDownload);
            var fileName = "test.json";
            var mimeType = "text/plain";
            var fileBytes = Encoding.ASCII.GetBytes(jsonString);
            return new FileContentResult(fileBytes, mimeType)
            {
                FileDownloadName = fileName
            };
        }

Mission

  public class Mission
    {
        public int Id { get; set; }
        public string name { get; set; }
    }

result:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文