Node.JS - Encoding images in base64 using Buffer
I'm trying to encode an image using base64 in Node.JS to pass along to the PostageApp API as an atta开发者_Python百科chment. I thought I had it working but it attaches a 1K file that isn't exactly what I was looking for.
Here's my code:
var base64data;
fs.readFile(attachment, function(err, data) {
base64data = new Buffer(data).toString('base64');
});
And here's the part of the API call I am making:
attachments: {
"attachment.txt" : {
content_type: "application/octet-stream",
content: base64data
},
}
I'm a bit lost, not being so great with Node, but I thought it would work. Any help would be appreciated!
fs.readFile(attachment, function(err, data) {
var base64data = new Buffer(data).toString('base64');
[your API call here]
});
It takes some time until the results are there, so by the time you've got the data, the outer scopes execution is already over.
Just specify "base64" as the encoding. Per the docs:
If no encoding is specified, then the raw buffer is returned.
fs.readFile(attachment, {encoding: 'base64'}, function(err, base64data) {
[your API call here]
});
As of March 2023, I found this solution to be useful because the accepted answer is now deprecated. Use new Buffer.from
along with base64
parameter instead of new Buffer
does the trick.
base64data = new Buffer.from(data, 'base64').toString('base64');
精彩评论