Sample rails4 application with REST API which uses

2019-09-14 01:37发布

问题:

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 .

回答1:

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)

  private

  def picture_data_provided?
    !self.picture_data.blank?
  end

  def decode_picture_data
    # If cover_image_data is set, decode it and hand it over to Paperclip
    data = StringIO.new(Base64.decode64(self.picture_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
  end
end

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.