Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest POST to PHP removes plus-signs

I'm posting a JPEG file from a HTML5 canvas element as a string to PHP using:

function createJPG() {
    var dataUrl = document.getElementById('canvas').childNodes[4].toDataURL("image/jpeg");
    console.log(dataUrl);
    var params = "theimage=" + dataUrl;
    var http = new XMLHttpRequest();
    http.open("POST", "/avatar/php/save-avatar.php", true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.send(params);
}

Everything is fine, the dataUrl is correct (in the console) and contains a valid JPEG file. But when I retrieve it with PHP, all the plus-signs are replaced by spaces?

The PHP-code:

$name = "image.jpg";
$data=$_POST['theimage'];

file_put_contents($name, base64_decode(substr($data, strpos($data, ",")+1)));
file_put_contents("../images/avatars/uploads/generated" . rand(0,200) . ".txt", $data);

I use the text file to see what the data looks like since I can't bother to figure out how to echo back to the JS :). The text file contains the exact same data as the JS console logs, but without the +'es and with spaces instead, which results in the JPEG files being corrupt.

What should I do?

like image 560
Rein Avatar asked Feb 22 '23 21:02

Rein


1 Answers

It doesn't remove them. + means "a space" in application/x-www-form-urlencoded data. So they get converted to spaces when the URI is decoded on the server.

As always for taking some data and putting it into a URL, you need to encode it:

var params = "theimage=" + encodeURIComponent(dataUrl);
like image 155
Quentin Avatar answered Mar 06 '23 09:03

Quentin