在React(客户端)上传.json文件并发送给Node(服务器端)

我想要一个用户能够浏览他们的本地文件select一个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> ) 

编辑使用下面的卢卡提示我尝试使其工作,但仍然没有运气。 我是这样做的。 使用npm Dropzone拖拽文件和superagent(我得到一些错误与获取)

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

这与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 }); 

另请参见如何使用FormData进行ajaxfile upload