mardi 11 août 2020

Modify Form Data before submitting in Rails Application

I have a form, where there are some fields and input[file] element. I'm using Cropper.js to crop the image. The issue I'm facing here is file input has the original image, but I have no way append the new cropped image to the form data before the form is submitted.

const readURL = function (input, target, preview, form_id) {
 let image = document.querySelector(preview);
 let file = document.querySelector(input).files[0];
 let cropper_canvas, imgSrc, reader, imgFile;
 if (file) {
  reader = new FileReader();
  reader.onload = (e) => {
   image.src = e.target.result;
   cropper_canvas = new Cropper(image);
  };
  reader.readAsDataURL(file);
 }

 $("#crop-button").click((e) => {
  imgSrc = cropper_canvas.getCroppedCanvas({ width: 300 }).toDataURL();
  cropper_canvas.getCroppedCanvas({ width: 300 }).toBlob(function(blob){
   imgFile = blob;
  });
  $(target).css("background-image", imgSrc);
  $(target).attr("style", `background-image: url(${imgSrc})`);

  $(`#edit_counselor_${form_id}`).submit(function () {
    var formData = new FormData(document.querySelector(`#edit_counselor_${form_id}`))
    formData.append("counselor[profile_image]", imgFile);
    return true;
  });
 });
};

Aucun commentaire:

Enregistrer un commentaire