如何将Base 64图像上传到Rails回形针
我已经在互联网上尝试了一百万种不同的教程,用于如何将我的iOS应用程序中的Base64图像上传到我的rails应用程序。 似乎无论我如何格式化请求它都不会被接受。
有谁知道如何将Base64图像上传到回形针?
我尝试将参数作为JSON发送
{ "thumbnail_image": "base64_data..." }
我也尝试附加数据url
{ "thumbnail_image": "data:image/jpeg;base64,alkwdjlaks..." }
我尝试发送带有和不带数据url的JSON对象
{ "thumbnail_image": { "filename": "thumbnail.jpg", "file_data": "base64_data...", "content_type": "image/jpeg" } }
我一直得到这些Paperclip::NoHandlerError
,然后它将Paperclip::NoHandlerError
数据转储到我的日志中。
您的Base64字符串似乎没问题。 你总是可以在这里查看
所以问题可能在Rails方面。 检查您收到的字符串是否与您发送的字符串完全相同。
使用Paperclip 4.2.1我设法以这样的方式保存Base64 GIF文件:
有:
class Thing has_attached_file :image
和POST属性:
{ "thumbnail_data:" "data:image/gif;base64,iVBORw0KGgo..." }
您所要做的就是找到合适的适配器并指定original_filename。 所以对于控制器来说:
def create image = Paperclip.io_adapters.for(params[:thumbnail_data]) image.original_filename = "something.gif" Thing.create!(image: image) ... end
AFAIK Paperclip可以更轻松地从3.5.0版本中保存base64。
希望有所帮助!
这就是我过去的做法,它基本上是一种蛮力的方法,不确定回形针是否在最近的版本中增加了更好的支持,但这应该工作
class FooBar < ActiveRecord::Base has_attached_file :thumbnail_image validates_attachment_content_type :thumbnail_image, content_type: %w(image/jpeg image/jpg image/png image/gif), message: "is not gif, png, jpg, or jpeg." attr_accessor :base64_thumbnail_image # call this explicitly from the controller or in an after_save callback # after setting the base64_thumbnail_image attribute def save_base64_thumbnail_image if base64_thumbnail_image.present? file_path = "tmp/foo_bar_thumbnail_image_#{self.id}.png" File.open(file_path, 'wb') { |f| f.write(Base64.decode64(base64_thumbnail_image)) } # set the paperclip attribute and let it do its thing self.thumbnail_image = File.new(file_path, 'r') end end end # params should be base64_thumbnail_image, not thumbnail_image in this case