AJAX 通过活动存储附件提交 Rails 表单



我有一个表单,我想用AJAX提交。该表单允许您将图片作为附件以及其他字段上传。现在使用纯轨道它工作得很好,我设置的 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!'
})
})
}

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

您正在对图像数据使用 .serialize。这是不可能的。 到目前为止,此链接最适合您阅读有关文件上传 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);
}

在这里如何异步上传文件?

最新更新