我有一个二进制数据字符串,我需要它作为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)发布于 2017-02-27 01:32:25
请勿对二进制数据使用raw StringIO。我发现没有人在现实世界中测试过StringIO。
bin = ["d9a1a2"].pack("H*")
puts bin.encoding
puts bin[0].unpack("H*")
puts "----"
io = StringIO.new bin
puts io.string.encoding
puts io.string[0].unpack("H*")
puts "----"
io = StringIO.new
io << bin
puts io.string.encoding
puts io.string[0].unpack("H*")
io.string.force_encoding Encoding::BINARY
puts io.string.encoding
puts io.string[0].unpack("H*")
puts "----"
io = StringIO.new
io.binmode
io << bin
puts io.string.encoding
puts io.string[0].unpack("H*")
io.string.force_encoding Encoding::BINARY
puts io.string.encoding
puts io.string[0].unpack("H*")
puts "----"
io = StringIO.new
io.set_encoding Encoding::BINARY
io << bin
puts io.string.encoding
puts io.string[0].unpack("H*")
puts "----"ruby-2.3.3
ASCII-8BIT
d9
----
ASCII-8BIT
d9
----
UTF-8
d9a1
ASCII-8BIT
d9
----
ASCII-8BIT
d9
ASCII-8BIT
d9
----
ASCII-8BIT
d9
----rbx-3.72
ASCII-8BIT
d9
----
ASCII-8BIT
d9
----
UTF-8
d9a1
ASCII-8BIT
d9
----
UTF-8
d9a1
ASCII-8BIT
d9
----
ASCII-8BIT
d9
----jruby-9.1.7.0
ASCII-8BIT
d9
----
ASCII-8BIT
d9
----
UTF-8
d9a1
ASCII-8BIT
d9
----
UTF-8
d9a1
ASCII-8BIT
d9
----
ASCII-8BIT
d9
----StringIO。binmode。它不是核磁共振专用的存根。io.set_encoding Encoding::BINARY或io.set_encoding Encoding::BINARYhttps://stackoverflow.com/questions/17633293
复制相似问题