1

I know that a similar question has been asked before but none of them helped me. up vote

I have written some JavaScript that allows the user to draw on the canvas in different colors and pen sizes. I want to upload the canvas to my server

This is my index.html:

    <html>
  <head>
  </head>
  <body>
     <canvas id="canvas"></canvas>
     <button id="button_clear" onclick="test()">Clear/upload canvas</button>

<script>
function test(){
var canvas  = document.getElementById("canvas");
var dataURL = canvas.toDataURL();
$.ajax({
  type: "POST",
  url: "script.php",
  data: {
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved');
});
}
</script>

script.php:

<?php
    // requires php5
    //define('UPLOAD_DIR', 'FBdraw/');
    $img = $_POST['imgBase64'];
    $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.';

?>

When I refresh the script.php page it saves a empty 0 kB image.

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • path is correct? $file – devpro Jan 13 '16 at 09:35
  • What kind of server? i.e. Operating system – Andreas Jan 13 '16 at 09:40
  • @devpro yep, it's being saved to the right place, if that's what you're asking. –  Jan 13 '16 at 10:24
  • not absolutely a duplicate but you may want to have a look at [this answer](http://stackoverflow.com/questions/34711715/phpjs-how-to-do-fileuploads-in-html-form-as-content-type-multipart-via-js/34713226#34713226) which has the benefit to directly send a file instead of a heavier dataURL. – Kaiido Jan 13 '16 at 11:42
  • thank you @Kaiido. That worked! –  Jan 13 '16 at 12:00
  • Then feel free to upvote ;-) Also, you may still want to have an answer as to why your code wasn't working ? Like that I would say we'll need more info from your side, like a debugging of all steps in your php code. But if you don't care, you can [delete] the question or I could vote to close as duplicate. – Kaiido Jan 13 '16 at 12:07
  • @Kaiido I'll add a solution, thanks! Also, do you know how I could now get the images and replace it as my canvas? Thank you so much! :) –  Jan 13 '16 at 12:22

0 Answers0