在 Rails 中使用 PaperClip 更改上传到 Amazon S3 的图像路径

Change path of images uploaded on Amazon S3 using PaperClip in Rails

如何更改使用回形针和 rails 上传的图像的路径。我希望路径位于我存储桶的 gov_id 文件夹中,并且图像只保留在那里,没有任何子文件夹。还有如何使图像的 url 遵循这种格式:“https://s3-ap-southeast-1.amazonaws.com/BUCKET_NAME/GOV_ID/IMAGE_NAME.EXTENSION” 注意:我的存储桶中有一个 gov_id 文件夹

我有一个看起来像这样的附件模型:

    class Attachment < ApplicationRecord
      belongs_to :attachable, polymorphic: true
      has_attached_file :image, :styles => {:thumb => "200x200#"},
                        :storage => :s3,
      validates_attachment :image, content_type: { content_type:     ["image/jpg", "image/jpeg", "image/png"] }
      validates_attachment :image, presence: true

      before_save :rename_file

      def rename_file
          extension = File.extname(image_file_name).gsub(/^\.+/, '')
          new_image_file_name = "gov_#{self.attachable.reference_code}.#{extension}"

          image.instance_write(:file_name, new_image_file_name)
      end
    end

这会存储上传到我的存储桶但不在 gov_id 文件夹中的图像。它转到 attachments/images/000/000/013/original url 变为“s3-ap-southeast-1.amazonaws.com/BUCKET_NAME/attachments/images/000/000/013/original/gov_UG2S463C.png?1500620951

问题是您试图为它分配一个新名称并成功,但您没有告诉它以 s3 理解的格式执行此操作。

您必须记住的是,s3 存储桶基于 keysobjects 工作。如果您查看 s3 存储桶,文件夹结构在大多数情况下只是为了展示。文件路径(包括文件名)本质上是键,对象是存储在那里的图像(在本例中)。

因此,您分配图像的关键是默认回形针路径(来源: paperclip docs),以 :file_name

结尾

在这个街区

has_attached_file :image, :styles => {:thumb => "200x200#"},
                  :storage => :s3,

您的 has_attached_file 末尾有一个逗号,我认为这意味着您删除了 bucket_name: 之类的内容(这很好,但是 next_time,请将任何敏感信息替换为占位符名称。它使问题更容易理解)。

您应该有一个 path: 符号与用于访问 s3 对象的密钥相关联。通常,回形针会自动为您生成它,但在这里您需要手动分配它。所以你应该能够添加这样的东西:

has_attached_file :image, :styles => {:thumb => "200x200#"},
                          :storage => s3, 
                          :path => "/gov_id/:class/:attachment/:style/:file_name"

如果您想要“000/000/001”,请输入 :path => "/gov_id/:class/:attachment/:id_partition/:style/:file_name"

我假设您想在其中添加样式,以便它可以适当地处理 :original 和 :thumb 样式。

此外,您可能想查看 Paperclip.interpolates

,而不是使用 before_save

类似于:

has_attached_file :image, :styles => {:thumb => "200x200#"},
                          :storage => s3, 
                          :path => "/gov_id/:class/:attachment/:style/:replaced_file_name"

Paperclip.interpolates :replaced_file_name do 
  extension = File.extname(image_file_name).gsub(/^\.+/, '')
  new_image_file_name = "gov_#{self.attachable.reference_code}.#{extension}"

  new_image_file_name
end