Question

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. 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.

    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. The client always gets the 200 http status.

I don't know what's wrong with this. I checked the raw base64 String with an online decoder. 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);
Was it helpful?

Solution

I believe you need to use encodeUriComponent(base64) before sending to server.

try sending a JSON object, and parsing the image on the client side.

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top