0

I'm trying to upload an image through a form to a url/api. I call handleImgUpload() method on submitting the form. The problem is that the request sent is empty. I think that new FormData(this) does not work with react or something.

There's another function that sets the image path.

handleImgUpload(e){
      e.preventDefault();
      $.ajax({
        url: "my url goes here", // Url to which the request is send
        type: "POST",             // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data){   // A function to be called if request succeeds
            console.log(new FormData(this));
        }
      });
}

here is the form:

<form id="uploadimage" onSubmit={this.handleImgUpload} action="" method="post" encType="multipart/form-data">
    <Row id="image_preview" className="row">
        <img id="previewing" src={this.state.imgPath}/>
    </Row>
    <div id="selectImage">
        <label>Select Your Image</label><br/>
        <input type="file" name="image" id="file" onChange={this.handleImgChange} required />
        <Button type="submit" className="btn btn-primary" id="upload">Upload</Button>
    </div>
</form>
ayakhaled
  • 71
  • 1
  • 1
  • 10
  • 1
    Possible duplicate of [jQuery Ajax File Upload](http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – Andy Ray Dec 31 '16 at 23:28
  • @AndyRay might be a duplicate, but not of that question. The problem here is incorrect usage of `this` – azium Dec 31 '16 at 23:32
  • But that's probably a useful link to keep here though, in case OP runs into further issues – azium Dec 31 '16 at 23:33

1 Answers1

0

this is going to be the React component, not the form, which can be found in event.target

handleImgUpload(e) {
  e.preventDefault()
  let formData = new FormData(e.target)

  for (let [key, val] of d.entries()) {
    console.log(key, val) <-- should log the correct form data
  }

  // ajax stuff
}
azium
  • 20,056
  • 7
  • 57
  • 79