加载本地 Json 文件并使用 Javascript 将其存储在变量中
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>
)
}
我创建了一个小应用程序,可以将我的数据保存在 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>
)
}