如何以二进制形式写入临时文件

问题描述 投票:1回答:3

[通过以下方式尝试将字符串/解压缩的文件写入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

如何在File.open('/tmp/test.jpg', 'rb') do |file| file.write(unzipped_io.read) end 中执行此操作

ruby-on-rails ruby ruby-on-rails-5
3个回答
0
投票

我在一个旧的Ruby论坛帖子中遇到了该解决方案,所以我想在这里分享它,使人们更容易找到:


0
投票

另一种选择是temp_file = Tempfile.new([name, extension]) temp_file.binmode temp_file.write(unzipped_io.read)


0
投票

[IO.binwrite(path, file_content)将选项传递给接受Tempfile.newFile.open,特别是:

© www.soinside.com 2019 - 2024. All rights reserved.