0

I am having issues saving images to local file. Every other things look fine but the image won't just save. Here is a snippet of my code.

    function saveImage(){
    var xmlhttp;
    xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"));
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //do something with the response
        }
    }
    xmlhttp.open("POST","ajxstuff.php",true);
    var oldCanvas = document.getElementById('cvs').toDataURL("image/png");
    var img = new Image();
    img.src = oldCanvas;
    xmlhttp.setRequestHeader("Content-type", "application/upload")
    xmlhttp.send(oldCanvas);
}

Here is the the ajxstuff.php

<?php

if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data like you would with traditional post
    $rawImage=$GLOBALS['HTTP_RAW_POST_DATA'];

    // Remove the headers  
    $removeHeaders=substr($rawImage, strpos($rawImage, ",")+1);

    // decode it from base 64 and into image data only
    $decode=base64_decode($removeHeaders);

    // save to your server
    $saveName = 'C:\Users\Administrator\Downloads\image009.png';
    $fopen = fopen($saveName, 'wb' );
    fwrite( $fopen, $decode);
    fclose( $fopen );
}

?>
  • What actually happens when you run your code? Are there any errors? What do the errors say? – Kenster Jul 10 '15 at 15:27
  • I am actually using this to generate a report. It doesn't give any error. The reports shows without the graph. It doesn't get save in the specified directory. – Isiaq Abdul-Azeez Olugbenga Jul 10 '15 at 15:39
  • If you use jQuery to help with your AJAX it will mean that you have to write less extraneous code. Eg $.post('ajxstuff.php', function () { /*Callback function*/ }) – Richard Jul 11 '15 at 10:51

1 Answers1

0

OK, here's my revised answer: You could instead of sending the image as (what looks like) a file, send it as text - since that's what you get from toDataUrl() (a base64 encoded representation of the image).

$.post('ajxstuff.php',{
    myChart: document.getElementById('cvs').toDataURL()
}, function ()
{
    /* callback */
})

And in your PHP script the data would show up in $_POST['myChart'] - and you could write it to a file like this:

<?php
    $data = base64_decode($_POST['myChart']);
    file_put_contents('C:\Users\Administrator\Downloads\image009.png', $data);
?>
Richard
  • 4,809
  • 3
  • 27
  • 46