我的 Express 应用程序正在从浏览器接收 base64 编码的 PNG(使用 toDataURL() 从画布生成)并将其写入文件。但该文件不是有效的图像文件,“文件”实用程序只是将其标识为“数据”。
var body = req.rawBody,
base64Data = body.replace(/^data:image\/png;base64,/,""),
binaryData = new Buffer(base64Data, 'base64').toString('binary');
require("fs").writeFile("out.png", binaryData, "binary", function(err) {
console.log(err); // writes out file without error, but it's not a valid image
});
原文由 mahemoff 发布,翻译遵循 CC BY-SA 4.0 许可协议
我认为您转换数据的次数超出了您的需要。使用正确编码创建缓冲区后,只需将缓冲区写入文件即可。
new Buffer(…, ‘base64’) 通过将输入解释为 base64 编码字符串,将输入字符串转换为 Buffer,它只是一个字节数组。然后您可以将该字节数组写入文件。
更新
正如评论中提到的,
req.rawBody
不再是一个东西。 If you are usingexpress
/connect
then you should use thebodyParser()
middleware and usereq.body
, and if you are doing this using standard节点然后您需要聚合传入的data
事件Buffer
对象并在end
回调中进行此图像数据解析。