如何产生包含JSON结构的文件进行下载? [英] How to produce a file to download containing a JSON structure?

查看:137
本文介绍了如何产生包含JSON结构的文件进行下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有此方法.

I have this method in my controller.

public IActionResult Download()
{
  return Json(_context.Users);
}

我注意到它会生成正确的JSON结构,但它会在浏览器中呈现为普通文本.我希望将其下载到客户端计算机上.我该怎么办?

I noticed that it produces the correct JSON structure but it's being rendered in the browser as common text. I want it to be downloaded to the client's computer. How do I do that?

我不确定是否应该让我的对象像这样 流式传输,或者在我的计算机上创建文件硬盘并为其提供像这样.

I'm not sure if is should make my object to stream somehow like this or maybe create a file on my hard drive and serve it like this.

我找不到像我们在C#中惯用的那样简单而直接的东西.因此,我担心这里会缺少一个概念.

I can't find anything that strikes me as straight-forward and simple like we're used to in C#. So I fear that I'm missing a concept here.

推荐答案

将数据转换为字节,然后将这些字节转换为FileResult.返回FileResult后,浏览器将在显示文件"时执行其通常的操作,通常会提示用户或下载.

Convert the data into bytes then those bytes into a FileResult. You return the FileResult and the browser will do whatever it does normally when presented with a 'file', usually either prompt the user or download.

以下示例:

public ActionResult TESTSAVE()
    {
        var data = "YourDataHere";
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
        var output = new FileContentResult(bytes, "application/octet-stream");
        output.FileDownloadName = "download.txt";

        return output;
    }

在这种情况下,您只需将JSON数据作为字符串即可.

In your case you would simply take your JSON data as a string.

这篇关于如何产生包含JSON结构的文件进行下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆