3

i have this code, either the ajax isn't transferring the data correctly or my php doesn't work properly. i know the canvass is saving to data png it writes to the page. Is there a way to just convert it to a file and save it from javascript?

START JAVASCRIPT:-------------------

<-- get the canvass element and convert to data png -->

var canvas = document.getElementById("textCanvas"); 
var img = canvas.toDataURL("image/png");

<-- END the canvass element and convert to data png -->

<-- SEND to php file -->

var onmg = encodeURIComponent(img);
var xhr = new XMLHttpRequest();
var body = "img=" + onmg;
xhr.open('POST', "convertit.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Length", body.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(body);
xhr.onreadystatechange = function () {
   if (xhr.status == 200 && xhr.readyState == 4) {
     document.getElementById("div").innerHTML = xhr.responseText;
   } else {
     document.getElementById("div").innerHTML = 'loading';
     }
   }

<-- END send to php file -->

END JAVASCRIPT:-------------------

START PHP:-------------------

$img = $_POST['img']; 
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/uploads/file.png', $data);

END PHP:-------------------

5
  • $_POST[MyFileToConvert] should likely be $_POST['img'] Commented Oct 21, 2014 at 2:29
  • it is i changed that to post on here Commented Oct 21, 2014 at 3:05
  • i didnt solve my issue but i fixed the question thank you Commented Oct 21, 2014 at 3:06
  • Are you seeing some data written into /uploads/file.png at all? Commented Oct 21, 2014 at 3:37
  • when I echo the $data it does but the file doesn't upload. Commented Oct 21, 2014 at 4:06

1 Answer 1

3

changed the php to -------->

define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . 'txtimg.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

which i got from ----->http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html

-cheers works awesome :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.