Trouble saving canvas as image to the public file directory I've created a canvas via jQuery and need to save it back to the public file directory as an image, so I can access it like any other image.

I can create the file and save it, into the same file location as my save.php script, but unable to save it to the public file directory...

var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL("image/png");

$.ajax({
  type: "POST",
  url:  Drupal.settings.basePath + "mypath/save.php",
  data: { 
     imgBase64: dataURL
  }
})


Then the following php as called in save.php:

$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = 'public://' . uniqid() . 'myCanvas.png';
file_put_contents($fileName, $fileData);


excluding 'public://' . will happily save to the location specified in Drupal.settings.basePath + "mypath/...", but I'm unable to tell it to save to the public directory or even any directory structure...
You need to create a module, and define a menu path in it using hook_menu(), and the page callback for that script will be your upload script.

function hook_menu()
{
  $menu['mymodule/upload'] = array
  (
    'title' =&gt; 'upload',
    'page callback' =&gt; 'mymodule_upload_callback',
    'access callback' =&gt; TRUE
  );

  return $menu;
}


Note that you'll need to name your hook in line with Drupal hook naming conventions: https://www.drupal.org/docs/7/creating-custom-modules/understanding-the-hook-system-for-drupal-modules

Then your upload callback:

function mymodule_upload_callback()
{
  // Handle your upload here. You will have
  // access to public:// and the rest of the Drupal API.

  // call drupal_exit at the end() to prevent your
  // script from going past this point.
  drupal_exit();
}