7

我在使用 Active Storage 时遇到问题。当我上传到 Amazon S3 时,不是将文件保存在具有原始名称的存储桶中,而是将myfile.zip其保存为key与该文件关联的文件。所以在 Cyber​​duck 我看到了这样的东西5YE1aJQuFYyWNr6BSHxhQ48t:没有任何文件扩展名。

我不确定 Rails 5 中是否有一些设置,或者它是否在 Amazon S3 中,但我花了几个小时谷歌搜索找出为什么会发生这种情况。

任何指针将不胜感激!

最好的问候,安德鲁

4

3 回答 3

8

这是由 ActiveStorage 设计的。该文件在 S3 上由它的密钥存储,没有扩展名,但是当 ActiveStorage 生成 URL 时,设置了处置和文件名

def url(key, expires_in:, filename:, disposition:, content_type:)
  instrument :url, key: key do |payload|
    generated_url = object_for(key).presigned_url :get, expires_in: expires_in.to_i,
      response_content_disposition: content_disposition_with(type: disposition, filename: filename),
      response_content_type: content_type

    payload[:url] = generated_url

    generated_url
  end

结尾

这样做可能是为了避免您在其他情况下遇到的文件名转义问题。

您可以在此处阅读有关Content-Disposition标题的更多信息。

于 2018-06-01T18:48:37.990 回答
5

您仍然可以使用文件名访问器引用名称。

class User < ApplicationRecord
  has_one_attached :photo
  ...
end

filename = User.first.photo.filename
于 2018-09-03T04:27:40.823 回答
4

为了在 S3 上拥有自定义文件名,您应该同时更新blob.keyS3 上的名称和名称。

blob.key主动存储使用远程图像路径和名称在 S3 上上传图像。

对于我的使用,我只使用猴子补丁更改了“图像变体”的名称,该补丁允许通过以下方式生成key终止filename

config/initializers/active_storate_variant.rb

ActiveStorage::Variant.class_eval do
  def key
    "variants/#{blob.key}/#{Digest::SHA256.hexdigest(variation.key)}/#{filename}"
  end
end

因此,当我需要图像变体的公共 url 时,我只需调用image.url('400x400')

这就是我的图像模型的自定义方式:

class Image < ApplicationRecord
  belongs_to :imageable, polymorphic: true
  has_one_attached :picture

  SIZES = { '400x400' => '400x400' }

  def url(size)
    return "https://placehold.it/#{size}" unless picture.attached?

    'https://my_s3_subdomain.amazonaws.com/' +
        picture.variant(resize: SIZES[size]).processed.key
  end

  ...

end

如果有人有更好的方法来做到这一点,我会很高兴看到它:)

于 2020-01-24T09:53:53.263 回答