javascript - react :write to json file or export/download [no server]

标签 javascript reactjs file-io blob

我对 JS/TS 中的文件 I/O 感到很困惑。我看到的大多数示例都适用于 DOM,并且具有基于浏览器的解决方案。

此外,我不明白如何使 fs 工作,它似乎需要一个 webpack 配置,我在其中使用 CRA 并且不想弹出。

在 React 组件中,我想从服务器获取一些数据,然后将它们保存为项目文件夹中的 JSON 文件(相同的路径、根目录、公共(public)文件夹,无论如何)或直接下载(不需要按钮)。

//data type just in case
inteface IAllData{ name:string; allData:IData[];}

所以在获取一些数据后想要将它们保存到 name.json

public componentDidMount(){
   this.fetchData().then(()=>this.saveData())
}

public async fetchData(){/* sets data in state*/}

public saveData(){
    const {myData}=this.state;
    const fileName=myData.name;
    const json=JSON.stringify(myData);
    const blob=new Blob([json],{type:'application/json'})
    /* How to write/download this blob as a file? */
}

在这里尝试 window.navigator.msSaveOrOpenBlob(blob, 'export.json'); 没有用

注意:我知道它有安全风险,不适合生产。最好将文件保存在项目文件夹中,但完全可以下载。

最佳答案

我有一个包含数据的 blob,我在 stackoverflow 上找到了一个解决方案并进行了一些操作,并成功下载为 xlsx 文件。我在下面添加我的代码,它也可能对您有所帮助。

const blob =  await res.blob(); // blob just as yours
const href = await URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.download = "file.xlsx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

编辑:您可以使用下面的函数,但一定要将 fileNamemyDatathis.state 切换到将在您的应用程序中工作。

const downloadFile = () => {
  const { myData } = this.state; // I am assuming that "this.state.myData"
                                 // is an object and I wrote it to file as
                                 // json

  // create file in browser
  const fileName = "my-file";
  const json = JSON.stringify(myData, null, 2);
  const blob = new Blob([json], { type: "application/json" });
  const href = URL.createObjectURL(blob);

  // create "a" HTLM element with href to file
  const link = document.createElement("a");
  link.href = href;
  link.download = fileName + ".json";
  document.body.appendChild(link);
  link.click();

  // clean up "a" element & remove ObjectURL
  document.body.removeChild(link);
  URL.revokeObjectURL(href);
}

有关 URL.createObjectURL 的更多文档在 MDN 上可用。使用 URL.revokeObjectURL 释放对象至关重要以防止内存泄漏。在上面的函数中,由于我们已经下载了文件,所以我们可以立即撤销该对象。

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them.

Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.

关于javascript - react :write to json file or export/download [no server],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55613438/

相关文章:

javascript - 为什么人们在他们的 javascript 代码周围添加 <!--//...//--> ?

javascript - DataTables:按列对表进行排序,固定 i++ 值?

javascript - 使用递归获取序列之和

java - Openfileinput 返回空指针异常

java - 通过java程序读取大型输入文件(10gb)

c# - 如何在创建文件夹时移动文件。目录.方法等

javascript - 安全错误 : The operation is insecure - window. history.pushState()

reactjs - 如何提高 Material UI 的整体动画速度

javascript - 如何连续排序和重新排序允许重复值的数字数组

javascript - 当页面加载时,react-facebook-login 中的 FacebookLogin 会被自动调用