繁体   English   中英

Rails API回形针。 上传图像将其转换为base 64并保存并检索

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

您好,我正在使用Ruby on Rails创建一个api。

我正在使用回形针宝石。

我有一个具有化身的profile模型。 我该如何允许用户上传头像? 目前我很失落。 问题是我可以使这种体系结构正常工作。 我是个初学者,所以任何帮助都会很棒。 我真的不确定如何获取base64转换后的图像并将该图像存储在数据库中。

我的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

这是我的更新操作:当前没有个人资料的头像,我正在尝试用一个头像进行更新。

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"

要求型号:

require "base64"

首先将其转换为Base64格式:

Base64 Ruby模块文档

Base64.encode64(your_content_here)

在View中检索就像:

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

注意:根据data:image / png部分中使用的内容更改图像格式。

该过程就像将文本数据保存到DB。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM