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
}
6
  • stackoverflow.com/questions/3582671/… Commented Mar 28, 2020 at 8:39
  • so you want to use a open file dialog? for the user to pick a filepath? Commented Mar 28, 2020 at 8:39
  • @Bobbey yes!!!! exactly Commented Mar 28, 2020 at 8:42
  • 1
    did you try the <input type=file> tag? you did not add any markup code to your question... Commented Mar 28, 2020 at 8:55
  • Please check stackoverflow.com/questions/46119987/… Commented Mar 28, 2020 at 9:02

1 Answer 1

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>
     )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.