[英]Load a local Json file and store it in a variable using Javascript
我创建了一个小应用程序,将我的数据保存在 JSON 文件中! 因为它都是本地的,所以我不需要 node.js 和后端技术。 经过一系列的函数,本地用Blob保存了一个JSON文件。
如何通过从计算机的文件系统中选择来创建将导入此文件的事件?
如果我在列表顶部写import data from './data.json';
有用! 我宁愿选择能够从文件系统的任何地方上传文件。
这允许我将文件保存在我想要的位置:
let file = new Blob([fileJSON], {type: 'application/json'});
let a = document.createElement("a");
a.href = URL.createObjectURL(file);
a.download = file;
a.click();
我如何通过每次选择路径来加载它?
loadDatas=()=>{
const dataJ = //something that allows me to go and choose the json file from my computer wherever it is
const parseIt = $.parseJSON(dataJ);
// do something
}
您可以尝试以下代码:
constructor(props){
super(props)
this.state={
file:null
}
this.inputRef = React.createRef()
}
openFileLoadingDialog = () => {
this.inputRef.current.click()
}
readURL=(e)=>{
let file = URL.createObjectURL(e.target.files[0])
if(this.state.file !== file)
{
this.setState({
file : file
})
}
}
render(){
return(
<div>
<input type="file" style={{display:"none"}} ref={this.inputRef} onChange={this.readURL}/>
<input type="button" value="open file" onClick={this.openFileLoadingDialog} />
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.