2

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);
7
  • How are you sending the file to the server? Commented Apr 26, 2014 at 10:28
  • I use XMLHttpRequest and post it to node/express Commented Apr 26, 2014 at 10:35
  • Are you using encodeURIComponent? Commented Apr 26, 2014 at 10:43
  • I have edited my Question with the Code of how I send the picture to node. Commented Apr 26, 2014 at 10:51
  • Why not just send the image file, why do you mess around with base64 to begin with ? Commented Apr 26, 2014 at 10:58

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution was right! I modified it a bit for my use and it works like a charm =) If I could I would upvote you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.