0

I need to upload a file in react and send it to the Node backend. Since I never worked with uploading and sending files before, this is a little troubling for me.

So far I found this:

// 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>
    );
  },
});

Source: https://fitacular.com/blog/react/2014/06/23/react-file-upload-base64/

But now I basically just end up with some sort of string. But I need to send that file via REST to my Express backend, which needs to save that file in CouchDB.

What is the best/easiest way to accomplish that?

MoeSattler
  • 6,684
  • 6
  • 24
  • 44

1 Answers1

0

If you are using body-parser, know that it handles json and url encoded forms, not multipart data ! You should use an other module. For more infos, give a look at : File uploading with Express 4.0: req.files undefined

Community
  • 1
  • 1
Léo Martin
  • 736
  • 7
  • 13