如何使用回形针在rails json api中上传图像?

时间:2016-04-16 06:36:52

标签: ruby-on-rails json rest paperclip

您好我在轨道上建立一个json api。我有一个模型类Product,它有一个与之关联的图像。 这是我的产品控制器

def create
         params[:product][:image] = parse_image_data(params[:product][:image]) if params[:product][:image]
         product = Product.new(product_params)
         product.image = params[:product][:image]
         if product.save
            render json: product, status: 201
        else
            render json: {error: product.errors}, status: 422
        end
    end
private
    def product_params
        params.require(:product).permit(:title,:description,:published,:product_type, :user_id, :image, address_attributes:[:address, :city_id])
    end

    def parse_image_data(image_data)
    @tempfile = Tempfile.new('item_image')
    @tempfile.binmode
    @tempfile.write Base64.decode64(image_data[:content])
    @tempfile.rewind

    uploaded_file = ActionDispatch::Http::UploadedFile.new(
      tempfile: @tempfile,
      filename: image_data[:filename]
    )

   uploaded_file.content_type = image_data[:content_type]
    uploaded_file
  end

  def clean_tempfile
    if @tempfile
      @tempfile.close
      @tempfile.unlink
    end
  end

产品型号:

class Product < ActiveRecord::Base
    belongs_to :user
    has_one :address
    has_attached_file :image, styles: { thumb: ["64x64#", :jpg],
                                        original: ['500x500>', :jpg] },
                              convert_options: { thumb: "-quality 75 -strip",
                                     original: "-quality 85 -strip" }

    validates :title, :description, :user_id, presence: true
    validates :product_type, numericality:{:greater_than => 0, :less_than_or_equal_to => 2}, presence: true
    accepts_nested_attributes_for :address
    validates_attachment :image,
                     content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] },
                     size: { in: 0..500.kilobytes }
end

我使用邮递员发送邮件请求,其中包含以下请求有效内容:

{
    "product": {
        "title":"Lumial 940",
        "description": "A black coloured phone found in Hudda Metro Station",
        "published": "true",
        "product_type":"2",
        "user_id":"1",
        "address_attributes":{
        "address": "Flat 16, Sharan Apartments, South City 1",
        "city_id": "2"
    },
    "image":{
        "filename": "minka.jpg",
         "content": "BASE64 STRING",
      "content_type": "image/jpeg"
    }
    }
}

但是在创建时,使用图像属性创建Product,但image_path属性在数据库中保存为null。我可以看到我的rails应用程序下的公共目录中写入的图像。我怎样才能保存image_path?

有人可以帮我解决这个问题吗?

0 个答案:

没有答案