I'm trying to encode an image using base64 in Node.JS to pass along to the PostageApp API as an attachment. 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!
from(data); //or Buffer. from(data, 'binary') let imgData = new Blob(binary. buffer, { type: 'application/octet-binary' }); let link = URL. createObjectURL(imgData); let img = new Image(); img.
The buffer class can be used to encode a string into a series of bytes. The Buffer. from() method takes a string as an input and converts it into Base64. The converted bytes can be changed again into String. The toString() method is used for converting the Base64 buffer back into the string format.
In Node. js, the Buffer. toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.
Base64 is an encoding algorithm that converts any characters, binary data, and even images or sound files into a readable string, which can be saved or transported over the network without data loss. The characters generated from Base64 encoding consist of Latin letters, digits, plus, and slash.
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] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With