【问题标题】:Upload .json file in React(client side) and send it to Node(server side)在 React(客户端)中上传 .json 文件并将其发送到 Node(服务器端)
【发布时间】:2017-09-18 11:06:30
【问题描述】:

我希望用户能够浏览他们的本地文件,选择一个 json 文件并上传它。我不想直接导入它。之后,我会将其发送到某个服务器 api,并将数据从 json 文件保存到数据库。问题是如何上传一个json文件以及如何将数据从它发送到服务器端api?

JSON 文件看起来像这样 {"people": [{"name": "Jon", age:23}, {"name": "Jane", age:25} ]}

我有一个像这样的反应组件

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

编辑 使用下面的 Luca 提示,我尝试使其工作,但仍然没有运气。我是这样做的。使用 npm Dropzone 拖动文件和超级代理(我在获取时遇到了一些错误)

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

【问题讨论】:

    标签: javascript json node.js reactjs


    【解决方案1】:

    这与 ReactJS 无关;您需要使用 fetch 或 AJAX 上传文件,因此您需要 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
    });
    

    另见How to use FormData for ajax file upload

    【讨论】:

    • 谢谢卢卡。这是朝着正确方向的推动。我在我的问题中更改了一些代码,但仍然没有运气。请您进一步指导我。
    • Dropzone 是一个不错的选择。随它去吧。你在服务器上用什么?纯 node.js 还是 express?你认为 req.body 是正确的地方吗?请看一下stackoverflow.com/questions/23114374/… BTW:要了解问题是在客户端还是在服务器上尝试检查您的浏览器请求内容
    • 谢谢卢卡,我设法让它工作了。 formData 是一个正确的方向。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多