如何使用php和ajax保存画布图像数据?

时间:2015-09-01 19:22:12

标签: javascript php jquery ajax html5

我在我的vps:http://permadi.com/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/

上遵循了本教程

testSave.php

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
  // Get the data
  $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

  // Remove the headers (data:,) part.
  // A real application should use them according to needs such as to check image type
  $filteredData=substr($imageData, strpos($imageData, ",")+1);

  // Need to decode before saving since the data we received is already base64 encoded
  $unencodedData=base64_decode($filteredData);

  //echo "unencodedData".$unencodedData;
 $randnum = rand(1111111111,9999999999);
  // Save file. This example uses a hard coded filename for testing,
  // but a real application can specify filename in POST variable
$tmpfname = tempnam("http://123.xx.xx.xx/test/tmp/", "FOO");
$fp = fopen(http://123.xx.xx.xx/test/test . uniqid() .".png","wb");
  fwrite( $fp, $unencodedData);
  fclose( $fp );
}
?>

JS

function saveViaAJAX()
{
    var testCanvas = document.getElementById("testCanvas");
    var canvasData = testCanvas.toDataURL("image/png");
    var postData = "canvasData="+canvasData;
    var debugConsole= document.getElementById("debugConsole");
    debugConsole.value=canvasData;

    //alert("canvasData ="+canvasData );
    var ajax = new XMLHttpRequest();
    ajax.open("POST",'testSave.php',true);
    ajax.setRequestHeader('Content-Type', 'canvas/upload');
    //ajax.setRequestHeader('Content-TypeLength', postData.length);


    ajax.onreadystatechange=function()
    {
        if (ajax.readyState == 4)
        {
            //alert(ajax.responseText);
            // Write out the filename.
                document.getElementById("debugFilenameConsole").innerHTML="Saved as<br><a target='_blank' href='"+ajax.responseText+"'>"+ajax.responseText+"</a><br>Reload this page to generate new image or click the filename to open the image file.";
        }
    }

    ajax.send(postData);
}

问题是当用户点击“通过ajax发送”时,服务器目录(http://prntscr.com/8bhmxa)中没有发送/生成的图像。这是结果:http://prntscr.com/8bhi62并且目录中的所有内容都保持不变。

在“保存为”

下生成的图像链接应该会发生什么

任何解决方案?

P.S。 无论如何用em回显图像链接?

1 个答案:

答案 0 :(得分:2)

问题在于你的AJAX。请参考这里的代码,用于使用php和ajax保存画布。 Link