[英]Active Storage failing to upload image attachment with AJAX Rails 5.2
[英]Rails form submission by AJAX with an active storage attachment
我有一個表格,我想使用 AJAX 提交。 該表單允許您將圖片作為附件上傳,以及其他字段。 現在使用純導軌它工作得很好,我設置的 AJAX 后 function 也可以工作......直到我嘗試上傳這個圖像文件。 它只是在沒有文件的情況下提交,就好像我沒有附加它一樣。 什么是正確的流程? ajax function
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 為您的圖像數據。 這是不可能的。 到目前為止,此鏈接是您閱讀有關文件上傳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);
}
在這里如何異步上傳文件?
解決方案是將我的表單包裝在FormData
object 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.