我有一串二进制数据,需要将其作为IO对象使用。因此,我尝试了以下代码:
r, w = IO.pipe()
w << data
但是它失败了,出现了以下错误:
Encoding::UndefinedConversionError ("\xD0" from ASCII-8BIT to UTF-8)
为什么它首先要转换为UTF-8?有没有一种方法可以强制IO::pipe方法进入二进制模式?
更多细节:
我正在尝试使用Mongoid驱动程序从MongoDB读取二进制数据(即Excel文件),然后将其转换为IO对象以便使用Spreadsheet gem读取它。 Spreadsheet#open要求提供文件路径或IO对象。
这是我的文件文档的样子:
class ImportedFile
include Mongoid::Document
field :file_name, type: String
field :binary_content, type: Moped::BSON::Binary
end
以下是我保存二进制数据的方法:
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
以下是我尝试阅读它的方式(不起作用):
imported_file = ImportedFile.find(file_id)
r, w = IO.pipe()
w << imported_file.binary_content.data
book = Spreadsheet.open r
io.set_encoding Encoding::BINARY
仍然是在MRI 3.0.1中的一个好的解决方案。 - Wayne Conrad