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.