LoginSignup
1

More than 5 years have passed since last update.

PaperclipでBase64エンコードされた画像を受け取る

Last updated at Posted at 2017-10-09

方法が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...

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1