Shuhail Kadavath Shuhail Kadavath - 1 year ago 91
reST (reStructuredText) Question

Sample rails4 application with REST API which uses paperclip to upload to Amazon S3

Can someone share me a sample application , that has REST APIs to upload images to Amazon S3 . I've googled a lot , but most of them are not working as expected .

A little help would be greatly appreciated .

Answer Source

For uploading images through API you can convert the images to base64 format in front end and send it to server. In, server you can convert the base64 data into the image and save it to S3 via paperclip.

class User < ActiveRecord::Base
    before_save :decode_picture_data, :if => :picture_data_provided?
    has_attached_file :avatar,
                    :storage => :s3, :s3_protocol => 'https',
                    :bucket => # S3_Bucket,
                    :url => '/user/:id/:basename_:id.:extension',
                    :s3_credentials => {
                        :access_key_id => # Access key id,
                        :secret_access_key => # Secret access key
                    :path => '/user/:id/:basename_:id.:extension',
                    :default_url => ""

  validates_attachment_content_type :avatar, :content_type => %w(image/jpeg image/jpg image/png)


  def picture_data_provided?

  def decode_picture_data
    # If cover_image_data is set, decode it and hand it over to Paperclip
    data =
    data.class.class_eval { attr_accessor :original_filename, :content_type }
    data.original_filename = SecureRandom.hex(16) + ".png"
    data.content_type = "image/png"
    self.avatar = data
    self.picture_data = nil

Here, picture_data is a column in User table which has the base64 data received from the client through API params.

You can specify your own S3 URL and path in above code.

In the above code the picture_data that came from the client side is decoded and saved in S3 via Paperclip.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download