我需要上传一个文件并将其发送到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中。
实现这一目标的最佳/最简单方法是什么?
答案 0 :(得分:0)
如果您使用正文解析器,请知道它处理json和url编码的表单,而不是多部分数据! 你应该使用其他模块。 有关更多信息,请查看:File uploading with Express 4.0: req.files undefined