如何将临时文件写成二进制文件
How to write a Tempfile as binary
尝试将字符串/解压缩文件写入 Tempfile 时:
temp_file = Tempfile.new([name, extension])
temp_file.write(unzipped_io.read)
当我对图像执行此操作时抛出以下错误:
Encoding::UndefinedConversionError - "\xFF" from ASCII-8BIT to UTF-8
在研究它时我发现这是因为 Ruby 尝试使用默认编码 (UTF-8) 写入文件。但是文件应该写成二进制文件,所以它会忽略任何文件特定的行为。
编写常规 File
您可以按以下方式执行此操作:
File.open('/tmp/test.jpg', 'rb') do |file|
file.write(unzipped_io.read)
end
如何在 Tempfile
中执行此操作
我在一个旧的 Ruby 论坛 post 遇到了解决方案,所以我想在这里分享它,让人们更容易找到:
https://www.ruby-forum.com/t/ruby-binary-temp-file/116791
显然 Tempfile
有一个未记录的方法 binmode
,它将写入模式更改为二进制,从而忽略任何编码问题:
temp_file = Tempfile.new([name, extension])
temp_file.binmode
temp_file.write(unzipped_io.read)
感谢 未知 2007 年在 ruby-forums.com 上提到它的人!
另一种选择是IO.binwrite(path, file_content)
Tempfile.new
将选项传递给 File.open
which accepts the options from IO.new
,特别是:
:binmode
If the value is truth value, same as “b” in argument mode
.
因此,要以二进制模式打开临时文件,您需要使用:
temp_file = Tempfile.new([name, extension], binmode: true)
temp_file.binmode? #=> true
temp_file.external_encoding #=> #<Encoding:ASCII-8BIT>
此外,您可能想使用 Tempfile.create
,它会占用一个块并在之后自动关闭并删除文件:
Tempfile.create([name, extension], binmode: true) do |temp_file|
temp_file.write(unzipped_io.read)
# ...
end
尝试将字符串/解压缩文件写入 Tempfile 时:
temp_file = Tempfile.new([name, extension])
temp_file.write(unzipped_io.read)
当我对图像执行此操作时抛出以下错误:
Encoding::UndefinedConversionError - "\xFF" from ASCII-8BIT to UTF-8
在研究它时我发现这是因为 Ruby 尝试使用默认编码 (UTF-8) 写入文件。但是文件应该写成二进制文件,所以它会忽略任何文件特定的行为。
编写常规 File
您可以按以下方式执行此操作:
File.open('/tmp/test.jpg', 'rb') do |file|
file.write(unzipped_io.read)
end
如何在 Tempfile
我在一个旧的 Ruby 论坛 post 遇到了解决方案,所以我想在这里分享它,让人们更容易找到:
https://www.ruby-forum.com/t/ruby-binary-temp-file/116791
显然 Tempfile
有一个未记录的方法 binmode
,它将写入模式更改为二进制,从而忽略任何编码问题:
temp_file = Tempfile.new([name, extension])
temp_file.binmode
temp_file.write(unzipped_io.read)
感谢 未知 2007 年在 ruby-forums.com 上提到它的人!
另一种选择是IO.binwrite(path, file_content)
Tempfile.new
将选项传递给 File.open
which accepts the options from IO.new
,特别是:
:binmode
If the value is truth value, same as “b” in argumentmode
.
因此,要以二进制模式打开临时文件,您需要使用:
temp_file = Tempfile.new([name, extension], binmode: true)
temp_file.binmode? #=> true
temp_file.external_encoding #=> #<Encoding:ASCII-8BIT>
此外,您可能想使用 Tempfile.create
,它会占用一个块并在之后自动关闭并删除文件:
Tempfile.create([name, extension], binmode: true) do |temp_file|
temp_file.write(unzipped_io.read)
# ...
end