【问题标题】:How to avoid getting UndefinedConversionError during decoding a file?如何避免在解码文件期间出现 UndefinedConversionError?
【发布时间】:2013-10-15 16:49:07
【问题描述】:

我有somefile,我想使用base64对其进行编码

File.open('data/somefile.edf').read.encoding
=> #<Encoding:UTF-8>

base64_string = Base64.encode64(open("data/somefile.edf").to_a.join)

然后我想解码那个文件

file = open('new_edf.edf', 'w') do |file| 
  file << Base64.decode64(base64_string)
end

但我得到一个错误:

Encoding::UndefinedConversionError: "\xE1" from ASCII-8BIT to UTF-8
from (pry):22:in `write'

【问题讨论】:

  • 只是出于好奇......我的解决方案是否有助于解决问题?

标签: ruby encoding base64 encode


【解决方案1】:

我认为问题在于默认情况下该文件是打开以在文本模式下写入的。要解决此问题,请使用二进制模式打开文件:

File.open('new_edf.edf', 'wb') { ... }

您也可以查看其他问题:Ruby 1.9 Base64 encoding write to file error

【讨论】:

  • 或 file.binmode
猜你喜欢
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
相关资源
最近更新 更多