我真的对JS / TS中的文件I / O感到困惑。我看到的大多数示例都适用于DOM,并且具有基于浏览器的解决方案。
此外,我不知道如何使fs
正常工作,它似乎需要Webpack配置,在此我使用CRA且不想弹出。
在React组件中,我想从服务器获取一些数据,然后将它们另存为JSON文件在项目文件夹(相同路径,根目录,公用文件夹,无论如何)中或直接下载(无需按钮)。 / p>
//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');
无效
注意::我知道它存在安全风险,不适合生产。最好将文件保存在项目文件夹中,但完全可以下载。
答案 0 :(得分:2)
对于像我这样的人,当您已经将JSON作为变量时,他们正在寻找一种更简单的解决方案:
<button
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(YOURJSON)
)}`}
download="filename.json"
>
{`Download Json`}
</button>
答案 1 :(得分:2)
<button
type="button"
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(YOURJSON)
)}`}
download="filename.json"
>
{`Download Json`}
</button>
如果您使用 Loic V 方法,只需在按钮元素上添加按钮的类型,应该可以正常工作。
答案 2 :(得分:0)
我有一个包含数据的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);
编辑:我已经为您的案例编写了一个函数,您可以使用以下函数,但是请注意“ fileName”(在我的案例中不在“ this.state”对象中)和“ myData”对象存储在“ this.state”对象。
const downloadFile = async () => {
const {myData} = this.state; // I am assuming that "this.state.myData"
// is an object and I wrote it to file as
// json
const fileName = "file";
const json = JSON.stringify(myData);
const blob = new Blob([json],{type:'application/json'});
const href = await URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.download = fileName + ".json";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}