1

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
})
Igor-Vuk
  • 3,551
  • 7
  • 30
  • 65

1 Answers1

2

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

Community
  • 1
  • 1
keul
  • 7,673
  • 20
  • 45
  • Thanks Luca. It's a push in right direction. I changed code a bit in my question but still no luck. Can you please instruct me further. – Igor-Vuk Apr 21 '17 at 15:04
  • Dropzone is a good choice. Go with it. What are you using on the server? Pure node.js or express? Are you usre that req.body is the right place to look at? Please take a look at http://stackoverflow.com/questions/23114374/file-uploading-with-express-4-0-req-files-undefined BTW: to understand is the issue is on the client or on the server try to inspect your browser request content – keul Apr 23 '17 at 08:30
  • Thanks Luca, I managed to make it work. formData was a right direction to go. – Igor-Vuk Apr 23 '17 at 12:32