【问题标题】:Rails 5.2 + Trix + ActiveStorageRails 5.2 + Trix + ActiveStorage
【发布时间】:2019-05-19 01:02:28
【问题描述】:

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

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

其他(可能)解决方案是:将 ActionText 与 Rails 5.2 一起使用。已经可以安全使用了吗?

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

    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}`,
            });
          }
        });
      }
    });
    

    希望对您有所帮助!

    【讨论】:

    • 谢谢!看起来不错的代码,但我已经在准备迁移到 RoR 6,这将“默认”启用此功能?
    • reals 6 实现了吗?
    • 太棒了!反其道而行之怎么办?在“trix-attachment-remove”处从服务器销毁?这不应该是默认值吗?
    猜你喜欢
    • 2020-05-30
    • 2019-10-23
    • 1970-01-01
    • 2019-06-12
    • 2018-02-02
    • 2019-05-19
    • 1970-01-01
    • 2018-10-20
    相关资源
    最近更新 更多