[英]Integration Rails active_storage with js uploaders
有沒有人將Rails ActiveStorage與任何js上傳器(例如Uppy或Dropzone)集成的示例?
我們可以使用activestorage的“ DirectUpload”類來實現。 這是javascript類,activestorage內部使用它來創建文件對象並將其直接上傳到指定的服務。
Dropzone要求指定一個URL,以便在上傳時可以在其中發布文件數據。 在這種情況下,您可以提供臨時URL,該URL用於向Dropzone提供成功消息,然后,您可以創建ActiveStorage DirectUpload對象以使用Active Storage上傳文件
Dropzone.options.folderUpload = {
maxFiles: 100,
url: temp_url,
clickable:false,
addRemoveLinks: false,
//timeout: 25000,
accept: function(file, done) {
},
init: function() {
this.on("success", function(file, response) {
// window.$('.dz-progress').hide();
// window$('.dz-size').hide();
// window.$('.dz-error-mark').hide();
toastr.success("File uploaded successfully");
});
}
}
使用處理文件更改事件並創建“ DirectUpload”類的對象,可以在附加文件后立即創建直接上傳文件。
這是簡單的例子
import { DirectUpload } from "activestorage"
// on file selection or change {
const url = element.dataset.directUploadUrl
const upload = new DirectUpload(file, url)
upload.create((error, blob) => {
if (error) {
// Handle the error
} else {
// Add an appropriately-named hidden input to the form with a value of blob.signed_id
$('<input>').attr({
type: 'hidden',
name: 'your_object[files][]',
value: blob.signed_id
}).appendTo('form');
}
})
// }
執行上傳到活動存儲后,您可以使用
$(“ form”)。submit()會將上傳的內容附加到您的rails模型對象上。 請記住,您必須更新其中帶有簽名ID的表單,否則它將不會將上傳內容附加到模型對象。
我最近在我的一個項目中使用了上述流程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.