How to Upload Image to AWS server from rails Controller

376 views Asked by At

Please Help for Upload image on AWS server in Controller.

I want following things to do.
1. Submit form data with image.
2. Get the image in controller and upload to AWS server.
3. No model coding for upload image to AWS.

Instead of write code in model as below

has_mongoid_attached_file :avatar, { path: ':class/:id/:style/:basename.:extension', storage: :s3, bucket: bucket_name, s3_credentials: { access_key_id: 'access_key_id', secret_access_key: 'secret_access_key' }, styles: { thumb: ['90x90^', :jpg], feature: ['220x142^', :jpg], show_page: ['720x420^', :jpg], preview: ['145x90^', :jpg] } }

I want to upload image directly from controller.

and only save the URL of uploaded image in database instead of below.

"attachment_file_name": "imagename.png", "attachment_content_type": "image/png", "attachment_file_size": 1235, "attachment_updated_at": TimeStamp,

i want to store only URL like this
avatar = https://s3.amazonaws.com/bucket_name/imagename.png

NOTE: My project in Rails 3.1.12 , Ruby 1.9.3p484 using mongoid

2

There are 2 answers

0
Pratap On

Hi friend your store S3 credential model this is wrong thing, you need to store s3 credential in separate yml file.

In Your config/production.rb

# config/environments/production.rb
     config.paperclip_defaults = {
       :storage => :s3,
       :s3_credentials => {
       :bucket => ENV['S3_BUCKET_NAME'],
       :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
       :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
      } 
     }

Writer your paperclip.rb

  config/initializers/paperclip.rb
  Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
  Paperclip::Attachment.default_options[:path]= '/:class/:attachment/:id_partition/:style/:filename'

In your model need to validate image type

  has_attached_file :avatar, styles: {
     thumb: '100x100>',
     square: '200x200#',
     medium: '300x300>'
  }

 # Validate the attached image is image/jpg, image/png, etc
 validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
0
Pratap On

You need to pass url option in model , like this

 has_mongoid_attached_file :avatar, {
        :url            => ':s3_alias_url',
  }