1
我希望用户能够浏览本地文件,选择一个json文件并上传它。我不想直接导入它。之后,我会将它发送到某个服务器api,并将数据从json文件保存到数据库。问题是如何上传json文件,以及如何从它发送数据到服务器端api?在React(客户端)上传.json文件并将其发送给节点(服务器端)
JSON文件看起来像这样{ “人”:[{ “Name”: “乔恩”,年龄:23},{ “名”: “简”,年龄: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悬浮窗的draging文件和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
})
由于卢卡。这是一个正确的方向。我在我的问题中改了一点代码,但仍然没有运气。你能不能指导我进一步。 –
Dropzone是一个不错的选择。去吧。 你在服务器上使用什么?纯粹的node.js还是express?你是否认为req.body是正确的地方?请看看http://stackoverflow.com/questions/23114374/file-uploading-with-express-4-0-req-files-undefined 顺便说一句:了解是问题出在客户端或服务器上尝试检查您的浏览器请求内容 –
谢谢卢卡,我设法让它工作。 formData是一个正确的方向。 –