【问题标题】:Encoding a file to base 64 Nodejs将文件编码为 base 64 Nodejs
【发布时间】:2017-11-29 12:21:14
【问题描述】:

我使用下面的代码将文件编码为 base64。

var bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');

我发现在文件中“”‘’ 字符存在问题,但" 没问题

当我们有It’s 时,节点对字符进行编码,但是当我解码时,我将其视为 It’s

这是我用来解码的 javascript:

fs.writeFile(reportPath, body.buffer, {encoding: 'base64'}

因此,一旦文件被编码和解码,这些时髦的字符就无法使用 - It’s

有人能解释一下吗?

【问题讨论】:

    标签: node.js encoding


    【解决方案1】:

    这是有帮助的代码。

    var bitmap = fs.readFileSync(file);
    
    // Remove the non-standard characters
    var tmp  = bitmap.toString().replace(/[“”‘’]/g,'');
    
    // Create a buffer from the string and return the results
    return new Buffer(tmp).toString('base64');
    

    【讨论】:

      【解决方案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 如果未指定字符集 Content-Type text/ 使用 ISO-8859-1。

      【讨论】:

      • 感谢您为我指明了正确的方向。我必须首先删除非标准 ascii 字符,它们是撇号(单引号和双引号),然后编码为 base 64。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多