在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
- 在AngularJS 1.5.0的$ http.get()中获得空的返回结果
- Node-Inspector无法打开Chrome浏览器抛出错误ENOENT
- “process.binding不支持”browersify gulp-sass
- expressionPOST req.body分析器是空的
- RangeError:在node_modules – > elasticsearch中超出最大调用堆栈大小
- 将hexstring转换为BYTE数组JS
- Node.js + Express – 无法连接。 ERR_CONNECTION_REFUSED
- Deepstream是否loggingRethinkDB中的整个文档?
- 如何在webpack包中包含subprocess?