【问题标题】:Uploading a file and sending it to the backend with React and Node使用 React 和 Node 上传文件并发送到后端
【发布时间】: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


【解决方案1】:

如果您使用的是 body-parser,请知道它处理的是 json 和 url 编码的表单,而不是多部分数据! 您应该使用其他模块。 欲了解更多信息,请查看:File uploading with Express 4.0: req.files undefined

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 2021-10-10
    • 2022-11-12
    • 1970-01-01
    • 2021-08-29
    • 2021-07-11
    • 2020-09-04
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多