首页 文章

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

提问于
浏览
1

如何使用回形针和导轨更改上传图像的路径 . 我希望路径位于我的存储桶的gov_id文件夹中,图像只保留在那里,没有任何子文件夹 . 以及如何使图像的网址遵循以下格式:“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文件夹中 . 它转到附件/ images / 000 / 000/013 / original并且网址变为“s3-ap-southeast-1.amazonaws.com/BUCKET_NAME/attachments/images/000/000/013/original/gov_UG2S463C.png?1500620951

1 回答

  • 0

    问题是你正在尝试为它分配一个新名称并取得成功,但你并没有告诉它以s3理解的格式执行此操作 .

    你必须要记住的是,s3桶基于键和对象工作 . 如果你看一个s3存储桶,文件夹结构只是为了显示,大部分 . 文件路径(包括文件名)本质上是键,对象是存储在那里的图像(在本例中) .

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

    在这个街区

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

    你在has_attached_file的末尾有一个逗号,我认为这意味着你删除了像 bucket_name: 这样的东西(这很好,但是next_time,用占位符名称替换任何敏感信息 . 它使问题更容易理解) .

    您应该有一个 path: 符号与用于访问s3对象的键相关联 . 通常,paperclip会自动为您生成此内容,但您需要手动分配它 . 所以你应该能够添加这样的东西:

    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
    

相关问题