0

I am using Fabric.js canvas library, and I want to save the canvas on the server. Converted it into data URL:

var canvasData = canvas.toDataURL();

and sent it to the server using Ajax:

let xhr = new XMLHttpRequest();
xhr.open("POST", "php/saveImg.php", true);
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
let data = xhr.response;
window.open(data);
}}};
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("canvasData=" + canvasData);

decoded the data and saved it in saveImg.php:

if(isset($_POST['canvasData'])){
$imageData = $_POST['canvasData'];
echo $imageData;

$filteredData = substr($imageData, strpos($imageData, ",") + 1);
$a = file_put_contents( "images/image1.png", base64_decode($filteredData));
}

When I look into image1.png, it is transparent with nothing in it (yet it has the right dimensions and a size of 40 KB).

When I check the value that is received in $_POST, I can see that the value of the data is deformed: some + characters have been removed and some other chars have been added.

Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
  • Does this answer your question? [uploading canvas context as image using ajax and php](https://stackoverflow.com/questions/11843115/uploading-canvas-context-as-image-using-ajax-and-php) – digijay Aug 19 '21 at 16:44
  • some other chars. Which chars can you share – Nadeem Taj Aug 19 '21 at 17:51

1 Answers1

0

Your POST data is not encoded properly, you can use encodeURIComponent to do this

xhr.send("canvasData=" + encodeURIComponent(canvasData));
Musa
  • 96,336
  • 17
  • 118
  • 137