4

我收到以下错误:

Encoding::UndefinedConversionError: "\x81" from ASCII-8BIT to UTF-8

以下都在 Ruby 1.8.7 中工作,所以我认为这与 Ruby 1.9 如何处理编码有关,但我不太确定如何解决它。我目前正在使用 Ruby 1.9.3。

  decode_base64_content = Base64.decode64(content) 

  File.open("index.txt", "w") do |f|
    f.write(decode_base64_content)
  end

内容类似于:

CgcZAAEAAABQcmVzZW50YXRpb24RMQAGSUIyQjdCNjBCLUZBRTMtMjVGMS1DQ0E1LTM1REM4NjBC
MDlCRgYCBklBMjk2OTQ4MC0yMkQyLURENzMtQUY5Ni1DNURDMDIyQTVFRjkGBAZJNUJCRTI3REYt
Q0QyRC03NkY0LTk1MUMtQzYxRkYxQjgxN0Y4BgYGSTg0QjM3M0FGLTVFNjEtMkMwMy1DMTBCLUNB
MUZCMDY0Q0NERQYIBkkwOTIwNDRBRC02QTQ5LTg0NzEtMzc5QS0yRjQxMzU2MUY0OUQGCgZJODlC
NDczOTUtOTk1MS01OTk1LTk4NDctNkU1NjI4RjhGNjYzBgwGSThCQ0RFM0VDLUMyREItMDkyNy1G
NTFFLTJGNDE4OEMzNURDMwYOBklGMDk5QkRDOC1GOEFDLTg1QjEtMjgzMC0yRjQ5RkZFMDFCNUEG
EAZJNTJCOEQ3RUItMzZEQi1CMjNELUU2MTYtMkY0QjUxNDIwMjBFBhIGSUM2RjkzNjgwLTFBNjMt
NzU5Qi0yOEE5LTUwMDc2NjZCOEYyNgYUBkk2MDIwRjg4Ni1BQTk4LTRBNDQtQjZGNS1DNDAyMTMz
NzEzOEQGFgZJRDFEMjcxMzYtQTkwQy0xRDBBLTc4RjAtQ0ExRUFCQzgzRUE1BhgGSUZBRDQzMjI1
LTUwODctNENEMy1ENjkzLUQ4Qzg0NDc3RTMyRAYaBklFMjc5NjA5Mi0xNUYzLUY4NkItMEFBQi0x
MUEzQjIwNEFBRTIGHAZJNERFNEYzNUItQzAyNy1DOTQ1LTY2MzUtMDE4NTZDRTdBMDM3Bh4GSUM4
NjA4RkI4LUI4RDEtMjM5RS04ODY4LUNBMjIzNUUwNjk5MAYgBkk4QjcxOEFDRi03NEE0LTA4REQt
QzZENC1DQTEyNDQwRTkzOUYGIgZJQjA3NTk0OEMtQzA3MS0wQTQ3LTYxNDQtNEU1OUIwN0QwQ0VF
BiQGSUM2M0VFQkU1LUZFOEEtRUVDMC1GNDFFLTc3QTI3Qzg2RDE1OAYmBkk5QkQ2M0NEQi02NDg2
LTM2OUQtMTY0NS0xMDIzMTQ5Njk1OUQGKAZJOTI3NDUzNDEtRUYzRC04MEU1LUZDQkUtQ0EyMTZG
Q0FGRTcyBioGSUI3MzlFMTBFLTk2M0QtMDA0Ny1EMkU1LUNBMjA2ODM2MjZFNgYsBkk4RUY5QkZB
Ni0wNDAyLTQwQUQtRjAxQi0xMTRBNDBFODMwRjMGLgZJQjY2N0YxODktNzQ4My05RkE4LTYwMDkt

持续约 3000 行。

如何解决此转换错误?上面的代码片段有效,但在 3000 行中,我认为 base64 解码方法使用了无效编码。谢谢!

4

1 回答 1

12

鉴于这"\x81"是一个控制字符,所以它不是任何形式的文本,您应该打开文件二进制文件:

File.open("index.txt", "wb") do |f|
  f.write(decode_base64_content)
end
于 2012-06-20T21:06:28.290 回答