9的Base64编码写入文件时出错

9的Base64编码写入文件时出错

本文介绍了Ruby 1.9的Base64编码写入文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

 编码:: UndefinedConversionError:\\ X81从ASCII-8BIT为UTF-8

在红宝石1.8.7以下的所有工作,所以我觉得这与Ruby 1.9的如何处理编码做的,但我不太知道如何解决它。我目前使用Ruby 1.9.3。

Where content is something like:

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

that continues for ~3000 lines.

How do I resolve this conversion error? The above snippet works but somewhere in the 3000 lines I think the base64 decode method uses an invalid encoding. Thanks!

解决方案

Given that "\x81" is a control character, so it's not text of any means, you should open the file binary:

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

这篇关于Ruby 1.9的Base64编码写入文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:51