使用json从iphone应用程序上传Rails图像

时间:2015-03-10 19:46:09

标签: ruby-on-rails json

我正在为iPhone应用程序使用Rails数据库。我创建了一个控制器:

def create
  @photomsg = Photomsg.new(photo_params)

  if @photomsg.save
    respond_to do |format|
      format.html { redirect_to(@photomsg, :notice => 'photomsg was     successfully created.') }
      format.json { render :json => @photomsg, :status => 1, :data => ''} 
    end
  else
    respond_to do |format|
      format.html { redirect_to(@photomsg, :notice => 'photomsg was fail to created.') }
      format.json { render :json => @photomsg.errors, :status => :unprocessable_entity} 

    end
  end
end 

并且params是

private
  def photo_params
    params.require(:photomsg).permit(:title, :image, :physician, :patient)
  end

我使用paperclip进行图片上传,模型看起来像

class Photomsg < ActiveRecord::Base     
attr_accessor :image_data

    has_attached_file :image, styles: {medium: ["300x300>", :png], thumb: ["100x100>", :png]}
  validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
    before_save :decode_image_data

    def decode_image_data
    # If image_data is present, it means that we were sent an image over
    # JSON and it needs to be decoded.  After decoding, the image is     processed
# normally via Paperclip.
if self.image_data.present?
    data = StringIO.new(Base64.decode64(self.image_data))
    data.class.class_eval {attr_accessor :original_filename, :content_type}
    data.original_filename = self.id.to_s + ".png"
    data.content_type = "image/png"

    self.image = data
end
  end
end

图片和其他字段上传在网络上运行良好,但是当从iPhone应用程序发送这些数据作为POST方法时,我正在使用以下网址为JSON网址:

http://infinite-depths-5848.herokuapp.com/photomsgs

路线如下

resources :photomsgs

0 个答案:

没有答案