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

Hello, I am creating an api using Ruby on Rails.

I use a paperclip gem.

I have a profile model that has an avatar. How can I let the user upload an avatar? Currently, I am completely lost. The problem is that I can get this architecture to work. I am completely new, so any help would be great. Im really not sure how to get a base64 converted image and save the image in a 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 upgrade action: Currently, the profile does not have an avatar, and I'm trying to update it.

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

Scheme

  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 
0
source share
2 answers

you can try downloading

  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" to the model

+3
source

Required in model:

 require "base64" 

First convert it to Base64 format:

Base64 Ruby Module Docs

 Base64.encode64(your_content_here) 

The extraction in the view is as follows:

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

Note. Change the image format depending on what you use in the data: image / png.

The process is similar to storing text data in a DB.

0
source

All Articles