1

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
}
TylerH
  • 20,799
  • 66
  • 75
  • 101

1 Answers1

0

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>
     )
}
Kuo-hsuan Hsu
  • 677
  • 1
  • 6
  • 12