Rails 由 AJAX 提交的带有活动存储附件的表单

Rails form submission by AJAX with an active storage attachment

我有一个要使用 AJAX 提交的表单。该表单允许您在其他字段中上传图片作为附件。现在使用纯 rails 它工作得很好,我设置的 AJAX post 功能也可以工作......直到我尝试上传这个图像文件。它只是在没有文件的情况下提交,就好像我没有附加它一样。正确的流程是什么? ajax 函数

function postInstrument() {
  $("form#new_instrument").submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: `http://localhost:3000/users/${userId}/instruments`,
      data: $(this).serialize(),
      dataType: "json",
      success: document.getElementById("new-instrument-form-div").innerHTML = 'Instrument Added!'
    })
  })

}

您正在为图像数据使用 .serialize。那是不可能的。 这篇 link 是目前为止关于文件上传的最佳读物 https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications

function FileUpload(img, file) {
  const reader = new FileReader();  
  this.ctrl = createThrobber(img);
  const xhr = new XMLHttpRequest();
  this.xhr = xhr;

  const self = this;
  this.xhr.upload.addEventListener("progress", function(e) {
        if (e.lengthComputable) {
          const percentage = Math.round((e.loaded * 100) / e.total);
          self.ctrl.update(percentage);
        }
      }, false);

  xhr.upload.addEventListener("load", function(e){
          self.ctrl.update(100);
          const canvas = self.ctrl.ctx.canvas;
          canvas.parentNode.removeChild(canvas);
      }, false);
  xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
  reader.onload = function(evt) {
    xhr.send(evt.target.result);
  };
  reader.readAsBinaryString(file);
}

这里How can I upload files asynchronously?

解决方案只是将我的表单包装在一个 FormData 对象中。