user3447572
user3447572

Reputation: 43

Base64 image send through Ajax encodeURIComponent

I'm trying send base64 converted image through ajax to a PHP backend. I have used encodeURIComponent for encode the base64 image and also I have to use encodeURI to encode the the parameters. Otherwise it keep giving me 403 Access denied error. When I send image like that image getting corrupt. When I just use encodeURIComponent to encode the image. and send without encode the parameters using encodeURI it works perfectly.(only in the local server.)

Following code only works in the local server (wamp)

                var img = canvas.toDataURL("image/png");

                var Parameters = "image=" + encodeURIComponent(img) + "&filename=" + name;

                $.ajax({
                    type: "POST",
                    url: "savePNG.php",
                    data: Parameters,
                    success: function (response) {
                        alert(response);
                    }
                });

And when I encode the data: encodeURI(Parameters), again it parse the data to the backend. but image get corrupt (I think because it encode two times.)

PHP backend code is like following.

$image = $_POST['image'];

$filename = $_POST['filename'];

$image = str_replace('data:image/png;base64,', '', $image);
$decoded = base64_decode($image);

file_put_contents($filename . ".png", $decoded, LOCK_EX);

echo $image;

Is there a way to make in work on the server without image getting corrupt.

Upvotes: 2

Views: 2236

Answers (1)

Dumindu Madushanka
Dumindu Madushanka

Reputation: 504

Use following trick.

JavaScript

var img = canvas.toDataURL("image/png");

var ajax = new XMLHttpRequest();
ajax.open("POST", 'savePNG.php', false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(img);

PHP Code

$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen("filename.png", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );

Upvotes: 2

Related Questions