4

I'm trying to save the canvas image to the server. I can save the file, but it's always 0 bytes. What's wrong with my code?

<script>
function test(){
var canvas  = document.getElementById("cvs");
var dataURL = canvas.toDataURL();

$.ajax({
  type: "POST",
  url: "upload.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 

});

}
</script>

php:

<?php    
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?> 
user3080392
  • 1,194
  • 5
  • 18
  • 35

1 Answers1

5

First you have to be sure that you have painted to the canvas after you defined the canvas variable and before you created the dataURL

Second, it seems like you are looking for img in this php line:

$img = $_POST['img'];

but in your javascript you are defining it as imgBase64 in:

data: { 
   imgBase64: dataURL
}

lastly you should be adding console.log(dataURL) after the dataURL has been created to be sure that there is anything in it.

NatureShade
  • 2,187
  • 1
  • 19
  • 27
  • Thanks. The problem was fixed when I replaced 'img' with 'imgBase64' as you suggested. I had tried to plug in 'dataUrl' but that wasn't working. Also, I had console.log(dataURL) in my code before posting, but took it out. – user3080392 Nov 30 '14 at 13:18