【发布时间】: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