简体   繁体   中英

AJAX Image Upload with React, Rails and Paperclip

Been searching but nothing comes close to my question, except this php question .

In my react component, using Rails 5, I could upload an image to S3 only if I submit the form; I don't want to refresh the page so I thought I could simply use ajax for that:

...

imageUpload(){
  var formData = $(this).serialize();
   $.ajax({
       url: '<url>',
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       processData: false,
       success: function (data) {
           console.log(data);
       },
       error: function () {
           alert("error in ajax form submission");
       }
   });
},

...

The html:

<form encType="multipart/form-data" acceptCharset="UTF-8">
  <input
    type="file"
    name="user[evidence]"
    id="user_evidence"
  />
  <button className="success button small" onClick={this.imageUpload}>Upload</button>
</form>

The goes to the update method (ajax url finds the method no problem):

...

def update
 u = User.find(1)
 u.update_attributes(user_evidence) # causing ajax to return an error
end

private
  def user_evidence
   params.require(:user).permit(:evidence)
  end

When an image is added and button is clicked, nothing uploads to s3. I guess I'm missing some sort of remote information with the ajax?

EDIT:

I have created a simple rails 5 app with this issue here .

You can't use this inside your method to reference the form. Try using refs .

<form ref="myForm" ...>
...
var formData = $(this.refs.myForm).serialize();

你有没有尝试过:

<form remote="true"...>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM