-1

I made an simple application how the users can edit canvas and send Canvas Base 64 data via ajax with PHP to create PNG images in this folder, the problem is it won't create PNG Images.

App web link; using Chrome, press F12 for inspection, check "Network" tab with XHR category, when you click "Upload" button, it will appear "canvasupload.php" http://www.powerupware.com/canva/

This PHP code:

<?php

    $name = $_POST['name']; //optional variable

    define ('UPLOAD_DIR', 'userCanvas/'); //folder to save image

    $img =  $_POST['CanvasPic']; //get from canvas base64 by user who posts via AJAX

    //base 64 string to convert image file properly
    $img = str_replace('data:image/png;base64,' '', $img);
    $img = str_replace(' ', '+', $img);


    //create PNG file
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png'; //outputs as image file in server with unique ID.

    $success = file_put_contents ($file, $data);

    print $success ? $file : 'Could not save the file!';

?>

After uploading this canvas, I got 200 OK with POST method, When I go to FTP, I open userCanvas folder and found no new png image files.

Ivan
  • 1,221
  • 2
  • 21
  • 43
  • Not sure what's wrong with your code, but [try this](http://stackoverflow.com/a/11511605/2629998) instead. –  Jul 06 '14 at 08:42
  • It may have something to do with where userCanvas exists since you're getting a success that the file was written. Try returning `realpath($file)` and see if it points to the same location you've FTP'd to. –  Jul 06 '14 at 08:48
  • Jeremy Miller, I added' print realpath($file); 'in return, I got blank string. – Ivan Jul 06 '14 at 09:02
  • André Daniel, changed different variables but no created PNG files. – Ivan Jul 06 '14 at 09:03

1 Answers1

2

I've figured out, for unknown reason, I created another code like this:

<?php

$img = $_POST['CanvasPic'];
define('UPLOAD_DIR', 'userCanvas/');


$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 : 'Could not save the file!';

?>

It worked, I can see new PNG files in this folder, I don't know why....

Ivan
  • 1,221
  • 2
  • 21
  • 43
  • +1 because I didn't realise you had to strip off data:image/png;base64 BEFORE you base64_decode - thanks! – Ukuser32 Apr 05 '17 at 11:29