ruby-on-rails – Rails 3 – 使用json上传图像

在我的Rails 3应用程序中,我有多个模型,每个模型都与另一个模型相关联.

用户模型

has_many :departments
accepts_nested_attributes_for :departments

部门模型

has_many :projects
accepts_nested_attributes_for :projects

我试图使用JSON通过postman REST client插入数据.我找到了一些格式,除了用户模型中有一个图像上传字段,我将使用PaperClip gem处理.

通过我的rails视图它工作正常,但如何使用邮递员上传图像?

要通过REST客户端上传,我需要与我的图像等效的JSON格式.

有没有办法在json中嵌入图像所以我可以使用postman rest客户端?

– 使用Base64

What is Base64
When you have some binary data that you want to ship across a network, you generally don’t do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know — some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you’ve entered a special character combination (like how FTP translates line endings).

So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings. Why 64? Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data’s going to end up on the other side of the wire uncorrupted.

– 摘自What is base 64 encoding used for?

因此,一种方法是在您的json请求中放置一个Base64字符串并让您的应用程序对其进行解码.

 # Your request
 {
    'user':{
     # .... 
         'picture':'GIF89a\xB4\x00\x1F\x00\xE7\xFD....'
     }
 }

这是你的模型可以做的

 class User < ActiveRecord::Base
   def convert_from_base64(image_data)
     data = StringIO.new(Base64.decode64(image_data))
     data.class.class_eval { attr_accessor :original_filename, :content_type }

     tmp = Tempfile.new("base64")
     tmp.write(data.read)
     tmp.close

     # only on *nix
     data.content_type = IO.popen(["file", "--brief", "--mime-type",tmp.path], 
        in: :close, err: :close).read.chomp
     data.original_filename = "picture." + data.content_type.split("/").last

     data
   end
 end


 # in your controller
 def create
   image_data = JSON.parse(params[:json])['user']['picture'] #or which ever field it is
   params[:user][:picture] = @user.convert_from_base64(image_data)
   # ....  
 end

但是快速浏览一下POSTMAN告诉我你必须对自己进行编码.

另外
你可以只传递一个url而不是数据 – 如果url指向网上可用的资源.

require "open-uri"

class User < ActiveRecord::Base
  def picture_from_url(url)
    self.picture = open(url)
  end
end
# then just do 
user.picture_from_url params[:user][:photo_url]

更新
Postman实际上允许您构建附加图像的发布请求.不是你在找什么?

翻译自:https://stackoverflow.com/questions/13911954/rails-3-use-json-to-upload-image

转载注明原文:ruby-on-rails – Rails 3 – 使用json上传图像