【问题标题】:How do I attach filenames with extensions in Rails 6 ActiveStorage?如何在 Rails 6 ActiveStorage 中附加带有扩展名的文件名?
【发布时间】:2021-07-06 10:11:16
【问题描述】:

我在 Rails 6 中使用 ActiveStorage。我很清楚 has_one_attachedhas_many_attached 的概念。 从那我有几个问题:

  1. 是否可以将带有扩展名的原始文件名而不是密钥上传到存储?
  2. 如何在 has_many_attached 期间指定存储路径。即我有 5 个文件需要存储在对象特定文件夹下。 例如/path/to/images/<image_id>/

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

    密钥是一个安全令牌,它从应用程序的 blob 指向存储在服务(S3 等)上的正确文件。尽管您不能使用某些东西来代替密钥,但是完全可以在附加时存储原始(或任何其他)文件/路径。例如,给定一个类的实例has_many_attachments :images

    message.images.attach(io: File.open('/wherever/thing1.png'), 
                          filename: '/path/to/images/thing1.png', 
                          content_type: 'image/png')
    

    filenamecontent_type与blob一起存储,查询时可以使用:

    message.images.blobs.find_by(filename: '/path/to/images/thing1.png')
    => #<ActiveStorage::Blob id: 1, key: "...", filename: "/path/to/images/thing1.png" ...>
    

    因此,如果您在特定文件夹下有五个文件,您只需打开/上传它们并在附加时指定适当的:filename

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      相关资源
      最近更新 更多