Ruby:二进制字符串到 IO

Rot*_*rel 6 ruby binary mongodb bson mongoid

我有一串二进制数据,我需要它作为 IO 对象。所以我试过这个:

r, w = IO.pipe()
w << data
Run Code Online (Sandbox Code Playgroud)

但它失败了这个错误:

Encoding::UndefinedConversionError ("\xD0" from ASCII-8BIT to UTF-8)
Run Code Online (Sandbox Code Playgroud)

为什么它首先尝试转换为 UTF-8?有没有办法将 IO::pipe 方法强制为二进制模式?

更多细节:

我正在尝试使用 Mongoid 驱动程序从 MongoDB 读取二进制数据(这是一个 Excel 文件),然后将其转换为 IO 对象,以便使用电子表格 gem 读取它。Spreadsheet#open 需要文件路径或 IO 对象。

这是我的文件文档的外观:

class ImportedFile
    include Mongoid::Document

    field :file_name, type: String
    field :binary_content, type: Moped::BSON::Binary
end
Run Code Online (Sandbox Code Playgroud)

这是我首先保存二进制数据的方式:

imported_file = ImportedFile.new
imported_file.file_name = uploaded_file.original_filename
imported_file.binary_content = Moped::BSON::Binary.new(:generic, uploaded_file.read)
imported_file.save
Run Code Online (Sandbox Code Playgroud)

这是我尝试阅读它的方式(不起作用):

imported_file = ImportedFile.find(file_id)

r, w = IO.pipe()
w << imported_file.binary_content.data
book = Spreadsheet.open r
Run Code Online (Sandbox Code Playgroud)

geo*_*ock 6

您可以StringIO为此使用 a :

require 'stringio'

io = StringIO.new(binary_data)
book = Spreadsheet.open(io)
Run Code Online (Sandbox Code Playgroud)