首页 > 解决方案 > 在nodejs中将二进制转换为base64

问题描述

有一个直接下载链接,可以根据 GET 请求下载 PDF。当我使用像邮递员这样的 REST 客户端发出获取请求时,响应中会收到二进制数据。我想将此数据转换为base64。现在,这个 base64 字符串需要传递给其他 API,后者又将文件发送到 WhatsApp 聊天。我在 WhatsApp 中成功收到了文件,但它完全是空白的。文件大小与源文件相同,页数也相同。

var axios = require('axios');
let base64;
var config = {
    method: 'get',
    encoding: null,
    url: '.................',
};
  
axios(config)
.then(function (response) {
    // console.log(response.data, "-----------------------------------\n");
    console.log(typeof response.data);

   // base64 = Buffer.from(response.data).toString('base64');
   // base64 = Buffer.from(response.data).toString('base64');
   // base64 = new Buffer(response.data, "binary");
   // base64 = Buffer.concat(response.data);
   // base64 = new Buffer(response.data, "base64");

   base64 = response.data.toString('base64');
   var data = {...........};

   var config2 = {
    method: 'post',
    url: '...........',
    headers: { 
    'Content-Type': 'application/json', 
    'x-auth-token': '...........', 
    'Host': '.............'
    },
    data : data
   };
  
   axios(config2)
   .then(function (response) {
     console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log("error while sending");
  });

})
.catch(function (error) {
  console.log(error, "error while requesting for the file");
});

我尝试了以下解决方案,但没有一个对我有用。

将 PDF 二进制数据编码为 base64 不适用于 NodeJS

标签: node.jsapirestpdfbase64

解决方案


推荐阅读