简体   繁体   中英

Upload .json file in React(client side) and send it to Node(server side)

I want for a user to be able to browse through their local files choose a json file and upload it. I dont want to import it directly. After that I would send it to some server api, and save the data from json file to database. The problem is how to upload a json file and how to send data from it to server side api?

JSON file would look like this {"people": [{"name": "Jon", age:23}, {"name": "Jane", age:25} ]}

I have a react component like this

   ...
   handleSubmit (e) {
     e.preventDefault()
     const fileUpload = this.refs.file.value;
   }

   render (): React.Element<any> {
      return (
        ...
        <form onSubmit={this.handleSubmit} encType="multipart/form-data">
          <input type="file" ref="file" accept=".json" id="fileInput" aria-describedby="fileHelp" />

        <button type="submit">Submit</button>
        </form>
    )

EDIT Using Luca hint below I try to make it work but still no luck. I did it like this. Using npm Dropzone for draging files and superagent(I was getting some errors with fetch)

...
  dropHandler (file) {
    let formData = new FormData()
    formData.append('file', file[0])

    request.post('/exchange')
      .send(formData)
      .end(function (err) {
        if (err) {
          console.log(err)
        }
      })
  }

   render () {
     return (
       ...
       <Dropzone disableClick={false} multiple={false} onDrop={this.dropHandler}>
          <div> Drop a json file, or click to add. < /div >
       </Dropzone>

    )

server.js

app.post('/exchange', (req, res) => {
  console.log(req.body)  //when i upload json file I am hitting this route but getting undefined here
})

This is not related to ReactJS; you need to upload a file using fetch or AJAX so you need FormData .

let formData = new FormData()
formData.append('file', fileUpload)
fetch(url, {
  method: 'post',
  headers: {
     // maybe you need headers, it depends from server implementation
  },
  body: formData
});

See also How to use FormData for ajax file upload

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