Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip and Amazon S3 how to do paths?

How do I create paths with paperclip when using Amazon S3?

My directory on my bucket is:

/image/:id/:filename

My model:

  has_attached_file :image,
    :storage => :s3,
    :bucket => 'mybucket',
    :s3_credentials => {
      :access_key_id => ENV['S3_KEY'],
      :secret_access_key => ENV['S3_SECRET']
    }
like image 734
Rails beginner Avatar asked Sep 19 '11 19:09

Rails beginner


People also ask

What is the path to S3 bucket?

An S3 bucket can be accessed through its URL. The URL format of a bucket is either of two options: http://s3.amazonaws.com/[bucket_name]/ http://[bucket_name].s3.amazonaws.com/

Can we move S3 bucket from one region to another?

The short answer is you can't migrate a S3 bucket from one region to another.

How do I explore S3 buckets?

In AWS Explorer, expand the Amazon S3 node, and double-click a bucket or open the context (right-click) menu for the bucket and choose Browse. In the Browse view of your bucket, choose Upload File or Upload Folder. In the File-Open dialog box, navigate to the files to upload, choose them, and then choose Open.


2 Answers

Try this:

  has_attached_file :image,
    :storage => :s3,
    :bucket => 'mybucket',
    :path => "/image/:id/:filename",
    :s3_credentials => {
      :access_key_id => ENV['S3_KEY'],
      :secret_access_key => ENV['S3_SECRET']
    }
like image 70
Tim Scollick Avatar answered Sep 29 '22 17:09

Tim Scollick


I wrote a post about it a few months back. I also wrote about how you can add properties from the class, for example not using an id (I don't like it) and using a token instead.

Read the post here...

The basics:

to get a path with an id

has_attached_file :avatar,
  :styles =>
  {
    :tiny => "48x48>",
    :preview => "175x175>",
    :large => "300x300>",
    :huge => "500x500>"
  },
  :storage => :s3,
  :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
  :path => ":class/:attachment/:id/:style.:extension",
  :bucket => 'lopsum',
  :default_url => "/images/photo01.jpg"

and, if you want to change it to something else...

has_attached_file :avatar,
  :styles =>
  {
    :tiny => "48x48>",
    :preview => "175x175>",
    :large => "300x300>",
    :huge => "500x500>"
  },
  :storage => :s3,
  :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
  :path => ":class/:attachment/:token/:style.:extension",
  :bucket => 'lopsum',
  :default_url => "/images/photo01.jpg"

and in an initializer

Paperclip.interpolates :token do |attachment, style|
  attachment.instance.token
end
like image 43
KensoDev Avatar answered Sep 29 '22 17:09

KensoDev