我使用下面的代码将文件编码为base64。 var bitmap = fs.readFileSync(file); 返回新缓冲区(位图).toString('base64');
我认为在文件中我们遇到了“”和“”字符的问题。 这很好用“
当我们它是时,它会对字符进行编码,在解码时,我将其视为 的伊达€™的
这是我的解码代码 - fs.writeFile(reportPath,body.buffer,{encoding:'base64'}
因此,一旦文件被编码和解码,它就会变得无法使用这些时髦的特征 - 它
有人可以对此有所了解吗?谢谢!
答案 0 :(得分:2)
这应该有效。 示例脚本:
const fs = require('fs')
const filepath = './testfile'
//write "it's" into the file
fs.writeFileSync(filepath,"it's")
//read the file
const file_buffer = fs.readFileSync(filepath);
//encode contents into base64
const contents_in_base64 = file_buffer.toString('base64');
//write into a new file, specifying base64 as the encoding (decodes)
fs.writeFileSync('./fileB64',contents_in_base64,{encoding:'base64'})
//file fileB64 should now contain "it's"
我怀疑你的原始文件没有utf-8编码,查看你的解码代码:
fs.writeFile(reportPath, body.buffer, {encoding: 'base64'})
我猜你的内容来自某种类型的http请求,因此内容可能不是utf-8编码的。看看这个: https://www.w3.org/International/articles/http-charset/index如果未指定charset,则Content-Type text /使用ISO-8859-1。
答案 1 :(得分:0)
这是帮助的代码。
var bitmap = fs.readFileSync(file);
//删除非标准字符
var tmp = bitmap.toString().replace(/[“”‘’]/g,'');
//从字符串
创建一个缓冲区var bitmap1 = new Buffer(tmp);
return bitmap1.toString('base64');