使用Paperclip上传base64图像 - Rails 4

时间:2015-04-28 21:40:21

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

我对Rails相对较新,并希望得到任何帮助。

我的网站接受base64格式的签名图片,我正在尝试使用Paperclip适配器对图像进行解码,并将其作为form属性保存到我的:signature模型中。我正在使用here(和here)给出的建议,建议使用以下代码:

模特:

class Thing
    has_attached_file :image

在控制器中:

def create
  image = Paperclip.io_adapters.for(params[:thumbnail_data]) 
  image.original_filename = "something.gif"
  Thing.create!(image: image)
  ...
end

我的假设是Thing.create!将Paperclip的模型属性:image的值设置为image变量的值,同时创建并保存新的Thing对象。我尝试在FormsController之前的@form.save(创建操作)中实现相同的代码,但是收到此错误:

undefined method `before_image_post_process' for #<Class:0x007f94a2a26de8>

我的FormsController

class FormsController < ApplicationController
  before_action :logged_in_user
  before_action :admin_user, only: :destroy

  def index
    @forms = Form.all #paginate
  end

  def show
    @form = Form.find(params[:id])
  end

  def new
    @form = Form.new
  end

  def create
    @form = Form.new(form_params)

    # Paperclip adaptor 
    signature = Paperclip.io_adapters.for(params[:base64])
    signature.original_filename = "something.png"

    # Attempt to submit image through Paperclip
    @form.signature = signature

    if @form.save
      flash[:success] = "The form has been successfully created!"
      redirect_to @form
    else
      render 'new'
    end
  end

  def edit
    @form = Form.find(params[:id])
  end

  def update
    @form = Form.find(params[:id])
    if @form.update_attributes(form_params)
      flash[:success] = "Form has been updated!"
      redirect_to @form
    else
      render 'edit'
    end
  end

  def destroy
    Form.find(params[:id]).destroy
    flash[:success] = "Form deleted"
    redirect_to forms_path
  end

  private

  def form_params
    params.require(:form).permit(:first_name, :last_name, :email, :phone, :address, :member_type, :base64)
  end
end

这是我的Form型号:

class Form < ActiveRecord::Base

  has_attached_file :signature
  validates_attachment_content_type :image, :content_type =>     ["image/jpg", "image/jpeg", "image/png", "image/gif"]

 end

1 个答案:

答案 0 :(得分:1)

假设您在视图中使用了Rails表单助手,并且根据您的form_params列表,:base64键不会位于params的顶层哈希,而是params[:form][:base64]

的一个级别