简体   繁体   English

如何在Node.js中将base64解码为图像文件?

[英]How to decode base64 to image file in Node.js?

I know this question is asked several times, but unfortunately nothing seems to work for me. 我知道这个问题已经被问过几次了,但是不幸的是,似乎没有什么对我有用。

I post the src of an img to my node/express. 我将img的src发布到我的节点/表达式。 It looks like this: 看起来像这样:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JF ... UUUUAFFFFAH/2Q==

The data is saved in picture. 数据保存在图片中。 I cut of the data:image-stuff and got the raw base64 and the filetype. 我剪切了data:image-stuff并得到了原始的base64和文件类型。

    var result = {
        "type":"",
        "data":""
    }

    var matches = picture.match(/^data:image\/([A-Za-z-+\/]+);base64,(.+)$/),response = {};
    result.type = matches[1];
    result.data = new Buffer(matches[2], 'base64');

    require('fs').writeFile(mediaFolder+'/test.'+result.type, result.data, "binary", function(err){
        res.status(500).send("error");
    });

    res.status(200).send("success");

When I try to open the saved image it says: Damaged or too big. 当我尝试打开保存的图像时,它说:损坏或太大。 I also tried to set the "binary" parameter in the writeFile methode. 我还尝试在writeFile方法中设置“ binary”参数。 The client always gets the 200 http status. 客户端始终获得200 http状态。

I don't know what's wrong with this. 我不知道这是怎么回事。 I checked the raw base64 String with an online decoder. 我用在线解码器检查了原始的base64字符串。 It worked perfectly. 效果很好。 I logged every string/match and everything looked okay to me. 我记录了每个字符串/匹配项,一切对我来说都还不错。

Any help would be nice to solve this Problem. 任何帮助都将很好解决这个问题。
Thanks in advance! 提前致谢!

EDIT: 编辑:

This is how I send the picture: 这是我发送图片的方式:

var base64Image = $('#show-picture').attr('src');
xmlhttp.open("POST","/webapp-ajax",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("picture="+base64Image);

I believe you need to use encodeUriComponent(base64) before sending to server. 我相信您需要在发送到服务器之前使用encodeUriComponent(base64)

try sending a JSON object, and parsing the image on the client side. 尝试发送JSON对象,然后在客户端解析图像。

For example: 例如:

var mimeType = image.split(';')[0];

var base64 = encodeUriComponent(image.split(',')[1]);

var imageData = {

  "mimeType" : mimeType,

  "src" : base64

}

...

xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(imageData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM