简体   繁体   中英

Load a local Json file and store it in a variable using Javascript

I created a small app that saves me data in a JSON file! Since it's all local I don't need node.js and backend technologies. After a series of functions, a JSON file is saved locally with Blob.

How do I create an event that will import this file by choosing it from the filesystem of the computer?

If I write at the top of the listing import data from './data.json'; it works! I'd rather rather have the option of being able to upload the file from anywhere on the filesystem.

this allows me to save the file where I want:

 let file = new Blob([fileJSON], {type: 'application/json'});
     let a = document.createElement("a");
     a.href = URL.createObjectURL(file);
     a.download = file;
     a.click();

how do I load it by going to choose the path every time?

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
}

You could try codes below:

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>
     )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM