Rails 5.2 + Trix + ActiveStorage

6

如何在配置了ActiveStorage的Rails 5.2中使用Trix编辑器上传图片?

我看到一些使用其他上传器的视频,但无法将其应用于ActiveStorage。

另一个(可能)的解决方案是:在Rails 5.2中使用ActionText。这样做是否安全?

1个回答

13

Active Storage具有直接上传js功能,您只需要添加:

//= require activestorage

将代码添加到你的application.js文件中,然后创建 trix-attachment-add 事件监听器:

document.addEventListener('trix-attachment-add', function (event) {
  var file = event.attachment.file;
  if (file) {
    var upload = new window.ActiveStorage.DirectUpload(file,'/rails/active_storage/direct_uploads', window);
    upload.create((error, attributes) => {
      if (error) {
        return false;
      } else {        
        return event.attachment.setAttributes({
          url: `/rails/active_storage/blobs/${attributes.signed_id}/${attributes.filename}`,
          href: `/rails/active_storage/blobs/${attributes.signed_id}/${attributes.filename}`,
        });
      }
    });
  }
});

希望这能对您有所帮助!

2
谢谢!代码看起来不错,但我已经在准备迁移到RoR 6,这将使此功能“默认启用”。 - Fernando
1
Reals 6 实现了这个吗? - thiebo
1
太好了!如何反过来操作?在“trix-attachment-remove”上从服务器上删除吗? 这不应该是默认设置吗? - sparkle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接