drizzy
drizzy

Reputation: 139

Trying to save base64 (image) file to server, it's empty

I'm trying to save a canvas image to a folder in my server however the file is empty upon inspection. I'm using AJAX to pass the encoded data to my php script, and then the php script is saving it to the server, empty.

This is the code I have:

JS/AJAX:

function convertCanvasToImage(thecanvas) {
                var ajax = new XMLHttpRequest();
                ajax.open("POST",'testSave.php',false);
                ajax.setRequestHeader('Content-Type', 'application/upload');
                ajax.send(canvasData);
            }

PHP (testSave.php):

    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

    $filteredData=substr($imageData, strpos($imageData, ",")+1);

    $unencodedData= base64_decode($filteredData);

    //echo "unencodedData".$unencodedData;

    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );

Thanks for any help in advance!

Upvotes: 3

Views: 2021

Answers (1)

ThinkingStiff
ThinkingStiff

Reputation: 65341

You're missing a line in your function to convert the <canvas> to data using the .toDataURL() function.

function convertCanvasToImage( thecanvas ) {
    var canvasData = thecanvas.toDataURL( 'image/png' ), //add this
        ajax = new XMLHttpRequest();
    ajax.open( 'POST', 'testSave.php', false );
    ajax.setRequestHeader( 'Content-Type', 'application/upload' );
    ajax.send( canvasData );
};

var thecanvas = document.getElementById( 'canvasId' );
convertCanvasToImage( thecanvas );

Upvotes: 1

Related Questions