方法がQiitaに載ってなく、探すのに手間取ったため書き残しておく。
概要
画像(ファイル)の受け取り方は主に下記2パターンらしい。
1. multipart/form-data
2. Base64エンコード
参照:https://qiita.com/mserizawa/items/7f1b9e5077fd3a9d336b
Paperclipに関して、
1のパターンについては、いくらでも記事が見つかるが、
2のパターンがあまり見つからない。
APIの実装時に2のパターンで作ってみようと思い、調べたので書き残す。
コードサンプル
いきなりですが…
class Image < ActiveRecord::Base
attr_accessor :image_name, :image_data
has_attached_file :image
before_validation :decode_base64_image
private
def decode_base64_image
if image_data && image_name
content_type = Mime::Type.lookup_by_extension(File.extname(image_name)[1..-1]).to_s
# => 'image/jpeg'などが取得できる
image_file = Paperclip.io_adapters.for("data:#{content_type};base64,#{image_data}")
# => 'data:#image/jpeg;base64,/9j/4AAQSkZJRgAB...'
image_file.original_filename = image_name
self.image = image_file
end
end
end
結論
↓の形が作れれば良いようです
data:#image/jpeg;base64,/9j/4AAQSkZJRgAB...