将RESPONSE BODY图像转换为base64

时间:2018-04-19 14:01:13

标签: javascript node.js base64

如何将图像转换为base64字符串?



var request = require('request');

let options = {
  url: imgUrl,
  headers: {
    "Authorization": imgauth
  },
  contentType: "base64"
};

//request response Content-type : 'image/png'
request(options, function(error, response, body) {
  var base64data = new Buffer(body, 'binary').toString('base64');
  console.log(base64data);
});




我使用上面的代码这样做,但它不起作用。

1 个答案:

答案 0 :(得分:0)

将请求encoding设置为null并获取文件内容,然后尝试使用节点的核心base64功能将其转换为buffer()

请参阅请求documentation herehere

const Request = require('request').defaults({ encoding: null });

let options = {
    url: imgUrl,
    headers: { "Authorization": imgauth }
};

Request.get(options, (error, response, body) => {
    if (!error && response.statusCode == 200) {
        let imagedata = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
        console.log(imagedata);
    }
});