Ami*_*avi 9 javascript file-io blob reactjs
我真的对 JS/TS 中的文件 I/O 感到困惑。我看到的大多数示例都适用于 DOM 并且具有基于浏览器的解决方案。
另外,我不明白如何fs工作,它似乎需要一个 webpack 配置,我使用 CRA 并且不想弹出。
在 React 组件中,我想从服务器获取一些数据,然后将它们作为 JSON 文件保存在项目文件夹中(相同的路径、根、公共文件夹,无论)或直接下载(不需要按钮)。
//data type just in case
inteface IAllData{ name:string; allData:IData[];}
Run Code Online (Sandbox Code Playgroud)
所以在获取一些数据后想要将它们保存到 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? */
}
Run Code Online (Sandbox Code Playgroud)
在这里尝试window.navigator.msSaveOrOpenBlob(blob, 'export.json');没有用
注意:我知道它有安全风险,它不适用于生产。首选将文件保存在项目文件夹中,但下载完全没问题。
kes*_*saf 20
我有一个包含数据的 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);
Run Code Online (Sandbox Code Playgroud)
编辑:我为您的案例编写了一个函数,您可以使用下面的函数,但要注意“fileName”(在我的案例中不在“this.state”对象中)和存储在“this.state”中的“myData”对象“ 目的。
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 10
对于像我这样的人,当您已经将 JSON 作为变量时,正在寻找更简单的解决方案:
<button
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(YOURJSON)
)}`}
download="filename.json"
>
{`Download Json`}
</button>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12129 次 |
| 最近记录: |