joeyk16
joeyk16

Reputation: 1415

Rails API Paperclip. Uploading image converting it to base 64 and saving it and retrieving it

Hello i am creating an api using Ruby on Rails.

I am using paperclip gem.

I have a profile model that has an avatar. How do i go about allowing a user to upload an avatar? Currently im quite lost. Problem is i can get this architecture to work. I am quite beginner so any help would be great. Im really unsure about how to get the base64 converted image and store the image in the database.

My Profile Model:

class Profile < ActiveRecord::Base
  belongs_to :user
  validates :user, presence: true

  before_validation :set_image

  has_attached_file :avatar, styles: {thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/

  #image_json is the image in base64 string

  def set_image
    StringIO.open(Base64.decode64(image_json)) do |data|
      data.class.class_eval { attr_accessor :original_filename, :content_type }
      data.original_filename = "file.gif"
      data.content_type = "image/gif"
      self.avatar = data
    end
  end
end

Here is my update action: Currently a profile no avatar and im trying to update it with one.

def update
  if @profile.update(profile_params)
    render json: @profile, status: :ok
  else
    render json: json_errors(@profile.errors), status: :unprocessable_entity
  end
end

Schema

  create_table "profiles", force: :cascade do |t|
    t.integer  "user_id"
    t.date     "birthday"
    t.text     "bio"
    t.string   "phone"
    t.string   "address_line_1"
    t.string   "address_line_2"
    t.string   "suburb"
    t.string   "state"
    t.string   "postcode"
    t.string   "country_code"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "avatar_file_name"
    t.string   "avatar_content_type"
    t.integer  "avatar_file_size"
    t.datetime "avatar_updated_at"
  end

Upvotes: 0

Views: 716

Answers (2)

aldrien.h
aldrien.h

Reputation: 3635

Requiring in Model:

require "base64"

First convert it to Base64 format:

Base64 Ruby module docs

Base64.encode64(your_content_here)

Retrieving in View, is like:

<img src="data:image/png;base64,YOUR_BASE64_HERE"/>

Note: Change the image format depending on what you are using in data:image/png section.

The process is like saving text data to DB.

Upvotes: 0

Pitabas Prathal
Pitabas Prathal

Reputation: 1012

you can try following for upload

 def set_image
  file = Paperclip.io_adapters.for(put base64 data of file)
  file.original_filename = "avatar_name"
  self.avatar = file
 end

add require "base64" in model

Upvotes: 3

Related Questions