Node.JS - 使用 Buffer 以 base64 编码图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7068309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.JS - Encoding images in base64 using Buffer
提问by JonLim
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.
我正在尝试在 Node.JS 中使用 base64 对图像进行编码,以作为附件传递给 PostageApp API。我以为我可以正常工作,但它附加了一个 1K 文件,这不是我想要的。
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:
这是我正在进行的 API 调用的一部分:
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!
我有点迷茫,对 Node 不太好,但我认为它会起作用。任何帮助,将不胜感激!
回答by thejh
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.
结果出现之前需要一些时间,因此当您获得数据时,外部作用域的执行已经结束。
回答by functionvoid
Just specify "base64" as the encoding. Per the docs:
只需指定“base64”作为编码。根据文档:
If no encoding is specified, then the raw buffer is returned.
如果未指定编码,则返回原始缓冲区。
fs.readFile(attachment, {encoding: 'base64'}, function(err, base64data) {
[your API call here]
});

