【问题标题】:Rails 5.2 Shrine and Tus server: Cannot create a custom folder structure to save filesRails 5.2 Shrine 和 Tus 服务器:无法创建自定义文件夹结构来保存文件
【发布时间】:2020-09-18 13:25:01
【问题描述】:

我正在使用 rails 5.2、Shrine 2.19 和 tus server 2.3 进行可恢复文件上传

routes.rb

  mount Tus::Server => '/files'

模型,file_resource.rb

class FileResource < ApplicationRecord
  # adds an `file` virtual attribute
  include ResumableFileUploader::Attachment.new(:file)

控制器/files_controller.rb

def create
      file = FileResource.new(permitted_params)
      ...
      file.save

config/initializers/shrine.rb


s3_options = {
  bucket: ENV['S3_MEDIA_BUCKET_NAME'],
  access_key_id: ENV['S3_ACCESS_KEY'],
  secret_access_key: ENV['S3_SECRET_ACCESS_KEY'],
  region: ENV['S3_REGION']
}

Shrine.storages = {
  cache: Shrine::Storage::S3.new(prefix: 'file_library/shrine_cache', **s3_options),
  store: Shrine::Storage::S3.new(**s3_options), # public: true,
  tus: Shrine::Storage::Tus.new
}

Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data

config/initializers/tus.rb

Tus::Server.opts[:storage] = Tus::Storage::S3.new(
  prefix: 'file_library',
  bucket: ENV['S3_MEDIA_BUCKET_NAME'],
  access_key_id: ENV['S3_ACCESS_KEY'],
  secret_access_key: ENV['S3_SECRET_ACCESS_KEY'],
  region: ENV['S3_REGION'],
  retry_limit: 3
)
Tus::Server.opts[:redirect_download] = true

我的问题是我无法覆盖 Shrine 类的 generate_location 方法以将文件存储在 AWS s3 的不同文件夹结构中。

所有文件都在s3://bucket/file_library/(tus.rb 中提供的前缀)内创建。我想要类似s3://bucket/file_library/:user_id/:parent_id/ 文件夹结构的东西。

我发现Tus配置覆盖了我所有的resumable_file_uploader类自定义选项,对上传没有影响。

resumable_file_uploader.rb

class ResumableFileUploader < Shrine
  plugin :validation_helpers  # NOT WORKS
  plugin :pretty_location     # NOT WORKS

  def generate_location(io, context = {})  # NOT WORKS
    f = context[:record]
    name = super # the default unique identifier

    puts "<<<<<<<<<<<<<<<<<<<<<<<<<<<<"*10

    ['users', f.author_id, f.parent_id, name].compact.join('/')
  end

  Attacher.validate do                    # NOT WORKS
    validate_max_size 15 * 1024 * 1024, message: 'is too large (max is 15 MB)'
  end

end

那么如何使用 tus 选项在 S3 中创建自定义文件夹结构(因为神社选项不起作用)?

【问题讨论】:

    标签: ruby amazon-s3 ruby-on-rails-5 shrine tus


    【解决方案1】:

    tus 服务器上传根本不会触及 Shrine,因此不会调用 #generate_location,而是由 tus-ruby-server 决定位置。

    请注意,tus 服务器应仅用作临时存储,您仍应使用 Shrine 将文件复制到永久存储(也称为“promote”),就像常规直接上传一样。升级时将调用#generate_location 方法,因此文件将被复制到所需位置;这一切都是在默认的 Shrine 设置下自动发生的。

    【讨论】:

    • 好的,谢谢。我在等你的答复。我将更改选项并查看。
    • 首先我将文件发送到 tus 端点 /files,如果成功保存在缓存中,我将调用创建文件 API,它执行 file.save,然后它应该调用 Shrine 对吗?
    • file.save 采用 tus 设置,而不是神殿。所以你更喜欢在file.save 之后再次执行ResumableFileUploader.upload(file_path) 以根据神社配置将其保存在 s3 中?
    • 是的,如果它没有将缓存文件提升为永久存储,请生成一个独立的示例来重现此行为。
    猜你喜欢
    • 2017-12-05
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多