的NodeJS:保存一个base64-CN $ C $光盘镜像到硬盘 [英] NodeJS: Saving a base64-encoded image to disk

查看:162
本文介绍了的NodeJS:保存一个base64-CN $ C $光盘镜像到硬盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的前preSS的应用程序正在接收来自浏览器的基于64位的连接codeD PNG(与toDataURL从帆布产生()),并将其写入文件。但该文件是不是有效的图像文件,文件工具简单地将其标识为数据。

  VAR体= req.rawBody,
  base64Data = body.replace(/ ^数据:影像\\ / PNG; BASE64,/,),
  binaryData =新的缓冲区(base64Data的base64')的toString('二进制')。要求(FS)。WriteFile的(out.png,binaryData,二进制,功能(错误){
  的console.log(ERR); //写出来的文件没有错误,但它不是一个有效的图像
});


解决方案

我觉得要转换的数据多一点比你需要。一旦你创建正确的编码缓冲区,你只需要编写缓冲区里的文件。

  VAR base64Data = req.rawBody.replace(/ ^数据:影像\\ / PNG; BASE64,/,);要求(FS)。WriteFile的(out.png,base64Data的base64',函数(ERR){
  的console.log(ERR);
});

新的缓冲区(...,'的base64')将输入字符串转换为缓冲区,这仅仅是一个字节数组,国米preting输入为Base64 EN codeD字符串。然后,你可以写一个字节数组到文件中。

更新

正如评论中提到, req.rawBody 不再是一个东西。如果您在使用前preSS / 连接,那么你应该使用 bodyParser( )中间件和使用 req.body ,如果你正在做这个使用标准的节点,那么你需要聚合传入数据事件缓存对象,并做到这一点的图像数据在结束回调解析。

My Express app is receiving a base64-encoded PNG from the browser (generated from canvas with toDataURL() ) and writing it to a file. But the file isn't a valid image file, and the "file" utility simply identifies it as "data".

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

解决方案

I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.

var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");

require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
  console.log(err);
});

new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.

Update

As mentioned in the comments, req.rawBody is no longer a thing. If you are using express/connect then you should use the bodyParser() middleware and use req.body, and if you are doing this using standard Node then you need to aggregate the incoming data event Buffer objects and do this image data parsing in the end callback.

这篇关于的NodeJS:保存一个base64-CN $ C $光盘镜像到硬盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆