Rails Carrierwave Base64图像上传

时间:2013-02-15 17:25:12

标签: ruby-on-rails ruby carrierwave

使用Carrierwave将图像从客户端上传到Rails后端的最佳方法是什么?现在我们的iOS开发人员将文件作为base64发送,所以请求就像这样:

"image_data"=>"/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAHqADAAQAAAABAAAAHgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAeAB4DAREAAhEBAxEB/8QAHwAAAQUBAQE....

所以,我的问题实际上是两个问题。我应该告诉他发送不同的文件格式吗?如果base64是发送这些文件的正确方法,那么我如何在carrierwave中处理它们?

3 个答案:

答案 0 :(得分:28)

我认为一种解决方案可以是将解码后的数据保存到文件中,然后将此文件分配给已安装的上传器。然后摆脱那个文件。

另一个(内存中)解决方案可以是这个:

# define class that extends IO with methods that are required by carrierwave
class CarrierStringIO < StringIO
  def original_filename
    # the real name does not matter
    "photo.jpeg"
  end

  def content_type
    # this should reflect real content type, but for this example it's ok
    "image/jpeg"
  end
end

# some model with carrierwave uploader
class SomeModel
  # the uploader
  mount_uploader :photo, PhotoUploader

  # this method will be called during standard assignment in your controller
  # (like `update_attributes`)
  def image_data=(data)
    # decode data and create stream on them
    io = CarrierStringIO.new(Base64.decode64(data))

    # this will do the thing (photo is mounted carrierwave uploader)
    self.photo = io
  end

end

答案 1 :(得分:6)

您可以使用Carrierwave-base64 Gem轻松实现此目的,您无需自己处理数据,只需添加gem并从中更改模型

mount_uploader :file, FileUploader

mount_base64_uploader :file, FileUploader

就是这样,现在你可以很容易地说:

Attachment.create(file: params[:file])

答案 2 :(得分:4)

旧问题,但我必须做类似的事情,从base64字符串上传图像,该字符串是通过json请求传递的。这就是我最终做的事情:

#some_controller.rb
def upload_image
  set_resource
  image = get_resource.decode_base64_image params[:image_string]
  begin
    if image && get_resource.update(avatar: image)
      render json: get_resource
    else
      render json: {success: false, message: "Failed to upload image. Please try after some time."}
    end
  ensure
    image.close
    image.unlink
  end
end

#some_model.rb
def decode_base64_image(encoded_file)
  decoded_file = Base64.decode64(encoded_file)
  file = Tempfile.new(['image','.jpg']) 
  file.binmode
  file.write decoded_file

  return file
end