我使用下面的代码将文件编码为 base64。
var bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');
我发现文件中的 “”
和 ‘’
字符有问题,但 "
当我们有 It's
时, Node 对字符进行编码,但是当我解码时,我将其视为
是
这是我用来解码的 javascript:
fs.writeFile(reportPath, body.buffer, {encoding: 'base64'}
因此,一旦文件被编码和解码,它就无法使用这些古怪的字符 - It's
任何人都可以阐明这一点吗?
最佳答案
这应该有效。 示例脚本:
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如果未指定字符集 Content-Type text/使用 ISO-8859-1。
关于node.js - 将文件编码为 base 64 Nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44763464/