Dre*_*ter 3 ruby-on-rails amazon-s3 amazon-web-services rails-activestorage
我在使用Active Storage时遇到问题。当我上传到Amazon S3时,与其像原始名称那样将文件保存在存储桶中,myfile.zip不如将key其另存为与该文件关联的文件。因此,在Cyberduck中,我看到的是这样的:5YE1aJQuFYyWNr6BSHxhQ48t。没有任何文件扩展名。
我不确定Rails 5中是否有某些设置,或者它是否在Amazon S3中,但是我花了数小时在Google上四处搜寻,以找出发生这种情况的原因。
任何指针将不胜感激!
最好的问候,安德鲁
这是由ActiveStorage设计的。该文件由其密钥存储,在S3上没有扩展名,但是当URL由ActiveStorage生成时,将设置处置和文件名。
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
Run Code Online (Sandbox Code Playgroud)
结束
这样做可能是为了避免否则会遇到文件名转义的问题。
您可以在此处阅读有关Content-Disposition标题的更多信息。
小智 5
您仍然可以使用文件名访问器引用名称。
class User < ApplicationRecord
has_one_attached :photo
...
end
filename = User.first.photo.filename
Run Code Online (Sandbox Code Playgroud)
为了在 S3 上拥有自定义文件名,您应该更新blob.keyS3 上的 和 名称。
主动存储使用blob.key远程图像路径和名称将图像上传到 S3 上。
对于我的使用,我仅使用 Monkey Patch 更改了“图像变体”的名称,该补丁允许生成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
Run Code Online (Sandbox Code Playgroud)
因此,当我需要图像变体的公共 url 时,我只需调用image.url('400x400')
这就是我的图像模型的定制方式:
ActiveStorage::Variant.class_eval do
def key
"variants/#{blob.key}/#{Digest::SHA256.hexdigest(variation.key)}/#{filename}"
end
end
Run Code Online (Sandbox Code Playgroud)
如果有人有更好的方法来做到这一点,我会很高兴看到:)
| 归档时间: |
|
| 查看次数: |
1382 次 |
| 最近记录: |