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

心不动则不痛 提交于 2019-12-25 09:16:54

问题


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.



来源:https://stackoverflow.com/questions/40460056/sample-rails4-application-with-rest-api-which-uses-paperclip-to-upload-to-amazon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!