簡體   English   中英

帶有 Amazon S3 的 Active Storage 不使用指定的文件名保存,而是使用文件密鑰保存

[英]Active Storage with Amazon S3 not saving with filename specified but using file key instead

我在使用 Active Storage 時遇到問題。 當我上傳到 Amazon S3 時,不是使用原始名稱(如myfile.zip將文件保存在存儲桶中, myfile.zip其保存為與該文件關聯的key 所以在 Cyber​​duck 中,我看到的是這樣的: 5YE1aJQuFYyWNr6BSHxhQ48t 沒有任何文件擴展名。

我不確定 Rails 5 中是否有一些設置,或者它是否在 Amazon S3 中,但我花了幾個小時在谷歌上搜索以找出發生這種情況的原因。

任何指針將不勝感激!

最好的問候,安德魯

這是設計使然,來自 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標頭的更多信息。

您仍然可以使用文件名訪問器引用名稱。

class User < ApplicationRecord
  has_one_attached :photo
  ...
end

filename = User.first.photo.filename

為了在 S3 上擁有自定義文件名,您應該同時更新blob.key和 S3 上的名稱。

活動存儲使用blob.key作為遠程圖像路徑和名稱在 S3 上上傳圖像。

對於我的用法,我只使用 Monkey Patch 更改了“圖像變體”的名稱,該補丁允許生成以filename結尾的key

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')

這是我的 Image 模型的自定義方式:

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

如果有人有更好的方法來做到這一點,我會很高興看到它:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM