Question

This is a newbie to ReactJS.

Could anyone please advise on what to use or how to have a form (with a few input boxes and a file selector) be uploaded in React?

Have been wrecking my nerves trying to use BlueImp JQuery-file-upload plugin. The error messages are cryptic and have been unsuccessful getting any useful help from google.

My code is as follows:

<form id="myForm" enctype="multipart/form-data" onSubmit={this.handleSubmit}>
  <input type="text" name="name">
  <input type="text" name="lastName">
  <input type="file" accept="image/*" name="myPic">
</form>

// Inside handleSubmit() of my component
$('#myForm").fileupload('add', {url: "myurl"});

Thanks!

No correct solution

OTHER TIPS

Using a jQuery plugin inside React is reasonable, but because React keeps its own virtual representation of the DOM you should avoid using jQuery selectors.

Use the event target to get a reference to the real DOM node when your form is submitted, and wrap it in a jQuery object to access the plugin:

React.createClass({
  handleSubmit: function(event) {
    $(event.target).fileupload('add', {url: "myurl"});
  },
  render: function() {
    return (
      <form enctype="multipart/form-data" onSubmit={this.handleSubmit}>
        <input type="text" name="name" />
        <input type="text" name="lastName" />
        <input type="file" accept="image/*" name="myPic" />
      </form>
    );
  }
});

I tried BlueImp but gave up and I'm using a solution modified from here to do it:

/** @jsx React.DOM */

var FileForm = React.createClass({
    getInitialState: function() {
        return {data_uri: null}
    },
    handleSubmit: function() {
        $.ajax({
            url: url,
            type: "POST",
            data: this.state.data_uri,
            success: function(data) {
                // do stuff
            }.bind(this),
            error: function(xhr, status, err) {
                // do stuff
            }.bind(this)
        });
        return false;
    },
    handleFile: function(e) {
        var reader = new FileReader();
        var file = e.target.files[0];

        reader.onload = function(upload) {
            this.setState({
                data_uri: upload.target.result
            }, () => console.log(this.state.data_uri));

        }.bind(this);

        reader.readAsDataURL(file);
    },
    render: function() {
        return (
            <form onSubmit={this.handleSubmit} encType="multipart/form-data">
                <input type="file" onChange={this.handleFile} />
                <input type="submit" value="Submit />
            </form>

        );
    }
});

From there your endpoint should be able to handle it.

To use BlueImp JQuery-file-upload plugin with ReactJS you need to set the replaceFileInput option to false. This is because when replaceFileInput is true (the default), BlueImp replaces the file input element with a new one each time a new file is selected .. and that is something ReactJS doesn't like.

Found out about this from: https://groups.google.com/d/msg/reactjs/lXUpL22Q1J8/-ibTaq-OJ6cJ

See the documentation on replaceFileInput here: https://github.com/blueimp/jQuery-File-Upload/wiki/Options#replacefileinput

Here's my way NO jQuery, using Parse.com

var UploadImageForm = React.createClass({
  getInitialState: function() {
    return {
      myFileName: "",
      myFileHandle: {}
    };
  },

  handleChange: function(event) {
    console.log("handleChange() fileName = " + event.target.files[0].name);
    console.log("handleChange() file handle = " + event.target.files[0]);
    this.setState( {myFileName: event.target.files[0].name} );
    this.setState( {myFileHandle: event.target.files[0]} );
  },

  handleSubmit: function(e) {
    e.preventDefault();
    console.log("INSIDE: handleSubmit()");
    console.log("fileName = " + this.state.myFileName); 
    console.log("this.state.myFileHandle = " + this.state.myFileHandle);

    if (this.state.myFileHandle) {
      console.log("INSIDE if test myFileHandle.length");
      var file = this.state.myFileHandle;
      var name = this.state.myFileName;
      var parseFile = new Parse.File(name, file);

      var myUser = new Parse.Object("TestObj");
      myUser.set("profilePicFile", parseFile);
      myUser.save()
        .then(function() {
          // The file has been saved to User.
          this.setState( {myFileHandle: null} );
          console.log("FILE SAVED to Object: Parse.com");
        }.bind(this), function(error) {
          // The file either could not be read, or could not be saved to Parse.
          console.log("ERROR: Parse.com " + error.code + " " + error.message);
        });;
    } // end if
  },

  render: function() {
      return  (
        <form onSubmit={this.handleSubmit}>
          <input type="file" onChange={this.handleChange} id="profilePhotoFileUpload" />
          <input type="submit" value="Post" />
        </form>
      );
  }
});

Here's mine:

It would be straightforward to modify to handle multiple files or to use native XHR instead of jQuery.

var FileUpload = React.createClass({
  handleFile: function(e) {
      var file = e.target.files[0];
      var formData = new FormData();
      formData.append('file',  file, file.name);
      $.ajax({
        url: URL,
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data) {
          console.log('success', data);
        },
        error: function() {
          console.error('error uploading file');
        },
      });
    },
    render: function() {
      return (
        <input className="btn btn-default btn-file" type="file" onChange={this.handleFile} accept="image/*;capture=camera"/>
      );
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top