我有一个二进制数据字符串,我需要它作为IO对象。所以我试了一下:
r, w = IO.pipe()
w << data但它失败了,并显示以下错误:
Encoding::UndefinedConversionError ("\xD0" from ASCII-8BIT to UTF-8)为什么它首先要尝试转换为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下面是我最初保存二进制数据的方式:
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发布于 2013-07-14 03:14:42
您可以使用StringIO来实现这一点:
require 'stringio'
io = StringIO.new(binary_data)
book = Spreadsheet.open(io)https://stackoverflow.com/questions/17633293
复制相似问题