简体   繁体   中英

convert RESPONSE BODY image to base64

How to convert an image into a base64 string?

 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); }); 

I have used the code above to do so, but it does not work.

Set request encoding to null and get the file content and then try to convert it to base64 using node's core buffer() functionality.

See request documentation here and here

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);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM