Rails API 回形针.上传图像将其转换为 base 64 并保存并检索它 [英] Rails API Paperclip. Uploading image converting it to base 64 and saving it and retrieving it

查看:36
本文介绍了Rails API 回形针.上传图像将其转换为 base 64 并保存并检索它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用 Ruby on Rails 创建一个 API.

Hello i am creating an api using Ruby on Rails.

我正在使用回形针宝石.

I am using paperclip gem.

我有一个带有头像的 profile 模型.如何让用户上传头像?目前我很迷茫.问题是我可以让这个架构工作.我是初学者,所以任何帮助都会很棒.我真的不确定如何获取 base64 转换后的图像并将图像存储在数据库中.

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.

我的Profile 模型:

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

架构

  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

推荐答案

可以尝试以下上传

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

在模型中添加require "base64"

这篇关于Rails API 回形针.上传图像将其转换为 base 64 并保存并检索它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆