【发布时间】:2015-12-22 16:08:01
【问题描述】:
我需要在 react 中上传一个文件并将其发送到 Node 后端。 由于我以前从未使用过上传和发送文件,这对我来说有点麻烦。
到目前为止,我发现了这个:
// this creates a React component that can be used in other components or
// used directly on the page with React.renderComponent
var FileForm = React.createClass({
// since we are starting off without any data, there is no initial value
getInitialState: function() {
return {
data_uri: null,
};
},
// prevent form from submitting; we are going to capture the file contents
handleSubmit: function(e) {
e.preventDefault();
},
// when a file is passed to the input field, retrieve the contents as a
// base64-encoded data URI and save it to the component's state
handleFile: function(e) {
var self = this;
var reader = new FileReader();
var file = e.target.files[0];
reader.onload = function(upload) {
self.setState({
data_uri: upload.target.result,
});
}
reader.readAsDataURL(file);
},
// return the structure to display and bind the onChange, onSubmit handlers
render: function() {
// since JSX is case sensitive, be sure to use 'encType'
return (
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" onChange={this.handleFile} />
</form>
);
},
});
来源:https://fitacular.com/blog/react/2014/06/23/react-file-upload-base64/
但现在我基本上只是以某种字符串结束。但我需要通过 REST 将该文件发送到我的 Express 后端,该后端需要将该文件保存在 CouchDB 中。
最好/最简单的方法是什么?
【问题讨论】:
-
你能把你的nodejs代码发给我用于文件上传吗?我也面临同样的问题
标签: node.js rest express reactjs