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

How can I change the path of the images I upload using paperclip and rails. I want the path to be inside my bucket's gov_id folder and the image just stays there without any subfolders. And also how to make the url of the image to follow this format: "https://s3-ap-southeast-1.amazonaws.com/BUCKET_NAME/GOV_ID/IMAGE_NAME.EXTENSION"
Note: I have a gov_id folder inside my bucket
I have an attachment model that looks like this:
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
this stores the image uploaded to my bucket but not inside the gov_id folder. It goes to attachments/images/000/000/013/original
And the url becomes "s3-ap-southeast-1.amazonaws.com/BUCKET_NAME/attachments/images/000/000/013/original/gov_UG2S463C.png?1500620951

The problem is that you are trying to assign it a new name and succeeding, but you aren't telling it to do this in a format that s3 understands.
The thing you have to remember, is that s3 buckets work based on keys and objects. If you look at an s3 bucket, the folder structure is just for show, for the most part. The file path (including the file name) is essentially the key, and the object is the image stored there (in this case).
So, the key you are assigning the image is the default paperclip path (source:
paperclip docs), which ends in :file_name
in this block
has_attached_file :image, :styles => {:thumb => "200x200#"},
:storage => :s3,
You have a comma at the end of your has_attached_file, which I assume means you deleted things like bucket_name: (which is fine, but next_time, replace any sensitive info with a placeholder name. it makes the problem easier to understand).
You should have a path: symbol associated with the key used to access the s3 object. Usually, paperclip auto-generates this for you, but here you want to manually assign it. So you should be able to add something like this:
has_attached_file :image, :styles => {:thumb => "200x200#"},
:storage => s3,
:path => "/gov_id/:class/:attachment/:style/:file_name"
If you would like the '000/000/001' then put :path => "/gov_id/:class/:attachment/:id_partition/:style/:file_name"
I assume you want to have style in there so that it will deal with both the :original and :thumb style appropriately.
Also, instead of using a before_save, you might want to look into Paperclip.interpolates
something like:
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

Related

Using model attribute as :filename when using paperclip gem

I'm getting an error when attempting to change the :filename of my paperclip attachment to equal an attribute on the class I'm attaching the paperclip file to.
When I use "#{self.company_name}" it errors out. Apparently in this scope, "self" is not Company. When I wrote this line I assumed that self is the instance of Company that I'm uploading this attachment to. Any idea how I can fix this? The Paperclip docs say to use ":filename" but I'd like to use the value of Company.company_name instead.
class Company < ActiveRecord::Base
include AliasAttrs
has_attached_file :company_logo, {
:storage => :ftp,
:path => "/logos/#{self.company_name}",
:url => FTP_CONFIG[:access_host]+"logos/:filename",
:ftp_servers => [
{
:host => FTP_CONFIG[:host],
:user => FTP_CONFIG[:user],
:password => FTP_CONFIG[:pass],
:port => 21 # optional, 21 by default
}
]
}
end
Update
I tried using the advice found in this post: https://robots.thoughtbot.com/paperclip-tips-and-updates
But now I am getting the following error when starting my server:
undefined method `interpolations' for Paperclip::Attachment:Class (NoMethodError)
It looks like the syntax for interpolations has changed. Updated it and it worked. Add the following to your model or create a paperclip.rb file in config/initializers
Paperclip.interpolates :company_name do |attachment, style|
attachment.instance.company_name
end

Upload paperclip images to s3 bucket

Not quite sure whats going on here, but when i try and upload an image to my s3 bucket i get this error
NameError in PostsController#create
uninitialized constant AWS::Core::ClientLogging
Rails.root: /home/richardlewis/Rails/myblog
Application Trace | Framework Trace | Full Trace
app/controllers/posts_controller.rb:41:in `create'
Im testing this in my dev environment at present. This is my current setup
Gemfile
#Paperclip and aws
gem "paperclip", "~> 3.0"
gem 'aws-sdk'
gem 'aws-s3'
Image Model
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
attr_accessible :photo
has_attached_file :photo, :styles => { :small_blog => "250x250#", :large_blog => "680x224#", :thumb => "95x95#" },
:storage => :s3,
:url => ":s3_domain_url",
:s3_protocol => 'http',
:path => "/images/:id/:style.:extension",
:s3_credentials => {
:bucket => ENV['AWS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
end
My ENV variables are stored in a env.rb file and loaded within initializers
has anyone come across this before?
Upgrading to the latest paperclip, 3.5.1, will fix this issue.

Paperclip - allow only PDF

How can allow to use upload only some kind of files, for example only PDF, Word or Excel files?
I use Paperclip gem.
Use content_type validation, like here:
validates_attachment :avatar, :content_type => { :content_type => "application/pdf" }

Rails paperclip plugin

I am a newbie. I am trying to upload an image through paperclip. The url and path code is working but the style option is not working. This is my code:
class User < ActiveRecord::Base
has_attached_file :image, :styles => { :small => "150x150>" },
:url => "/assets/users/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/users/:id/:style/:basename.:extension"
end
When I use the style it doesn't work. If I remove the style option it does work. Please help me out!
Not sure if this will work but try :style_:basename.:extension

Rails 3 - Restricting formats for action in resource routes

I have a resource defined in my routes.
resources :categories
And I have the following in my Category controller:
def show
#category = Category.find(params[:id])
respond_to do |format|
format.json { render :json => #category }
format.xml { render :xml => #category }
end
end
The controller action works fine for json and xml. However I do NOT want the controller to respond to html format requests. How can I only allow json and xml? This should only happen in the show action.
What is the best way to achieve this?
Also is there any good tips for DRYing up the respond_to block?
Thanks for your help.
I found that this seemed to work (thanks to #Pan for pointing me in the right direction):
resources :categories, :except => [:show]
resources :categories, :only => [:show], :defaults => { :format => 'json' }
The above seems to force the router into serving a format-less request, to the show action, as json by default.
You must wrap those routes in a scope if you want to restrict them to a specific format (e.g. html or json). Constraints unfortunately don't work as expected in this case.
This is an example of such a block...
scope :format => true, :constraints => { :format => 'json' } do
get '/bar' => "bar#index_with_json"
end
More information can be found here: https://github.com/rails/rails/issues/5548
This answer is copied from my previous answer here..
Rails Routes - Limiting the available formats for a resource
You could do the following in your routes.rb file to make sure that only the show action is constrained to json or xml:
resources :categories, :except => [:show]
resources :categories, :only => [:show], :constraints => {:format => /(json|xml)/}
If this doesn't work you could try explicitly matching the action:
resources :categories, :except => [:show]
match 'categories/:id.:format' => 'categories#show', :constraints => {:format => /(json|xml)/}
constraints was not working for POST requests and then I tried defaults it works for all.
namespace :api, :defaults => { :format => 'json' } do
namespace :v1 do
resources :users do
collection do
get 'profile'
end
end
post 'signup' => 'users#create'
post 'login' => 'user_sessions#create'
end
end
I was using Rails 4.2.7

Resources