【问题标题】:Rails API Paperclip. Uploading image converting it to base 64 and saving it and retrieving itRails API 回形针。上传图像将其转换为 base 64 并保存并检索它
【发布时间】:2016-06-16 09:20:56
【问题描述】:

您好,我正在使用 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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    您可以尝试关注上传

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

    在模型中添加require "base64"

    【讨论】:

      【解决方案2】:

      型号要求:

      require "base64"
      

      先转成Base64格式:

      Base64 Ruby module docs

      Base64.encode64(your_content_here)
      

      在视图中检索,就像:

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

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

      这个过程就像将文本数据保存到数据库。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-20
        • 1970-01-01
        • 2016-03-31
        • 1970-01-01
        • 2020-03-04
        • 1970-01-01
        相关资源
        最近更新 更多