Juan Martin
Juan Martin

Reputation: 89

How can I upload image using AJAX in rails5.1.6

I'm developing small site using Rails 5.1.6 and I've some trouble with uploading image. I need to upload using AJAX and I've found some answers by searching google but I haven't succeed yet. I'm using Rails 5.1.6 and used rails form tag that includes file_field. I want to upload image that is selected from file browser with AJAX.

Upvotes: 1

Views: 1449

Answers (2)

Adwin
Adwin

Reputation: 119

Full answer is here.

const uploadFile = element => {
  const formData = new FormData();
  formData.append("your_model[attribute_name]", element.target.files[0]);

  Rails.ajax({
    url: "your_model/:id",
    type: "PUT",
    beforeSend(xhr, options) {
      options.data = formData;
      return true;
    },
    success: response => {
      if (response.success) {
        alert("File uploaded successfully");
      }
      else {
        alert(response.errors.join("<br>"));
      }
    },
    error: () => {
      alert("ajax send error");
    }
  });
};

const documentOnReady = () => {
  const fileField = document.getElementById("ajax_file_upload");
  if (fileField) {
    fileField.addEventListener("change", uploadFile);
  }
}

document.addEventListener("turbolinks:load", documentOnReady);

Upvotes: 0

M. Urazov
M. Urazov

Reputation: 155

//f.file_field in html.erb will be compiled to <input type='file'>
//you can construct FormData manually, param by param:
var fileInput = document.querySelector('form input[type=file]');
var attachment = fileInput.files[0];
var formData = new FormData(); 
formData.append('email', 'Your Email');
formData.append('attachment', attachment, 'filename.jpg');

//In jQuery you would send it like this:

      $.ajax({
        url: "/profile/upload_image",
        type: "POST",
        beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
        data: "data=" + formData,
        success: function(data) {
          ...
        }
      });

I've also had that type of issue. You can send your image file's information to your rails API using AJAX and there you can upload image with the information. To upload a file via AJAX (e.g. from an ) you need to wrap your params in a FormData object.

Upvotes: 3

Related Questions