18

使用 Carrierwave 将图像从客户端上传到 Rails 后端的最佳方式是什么。现在我们的 iOS 开发人员正在以 base64 格式发送文件,因此请求如下所示:

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

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

4

3 回答 3

29

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

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

# 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
于 2013-02-15T21:59:32.773 回答
10

您可以使用Carrierwave-base64 Gem轻松实现这一点,您不必自己处理数据,您只需添加 gem 并更改您的模型

mount_uploader :file, FileUploader

mount_base64_uploader :file, FileUploader

就是这样,现在您可以轻松地说:

Attachment.create(file: params[:file])
于 2017-04-04T10:47:28.890 回答
6

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

#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
于 2015-06-17T07:06:37.963 回答