我正在尝试将画布图像保存到服务器中的文件夹中,但检查时文件为空。我正在使用AJAX将编码数据传递给我的php脚本,然后php脚本将其保存到服务器,为空。
这是我的代码:
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 );
提前感谢您的帮助!
答案 0 :(得分:1)
您在函数中缺少一行,可以使用<canvas>
函数将.toDataURL()
转换为数据。
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 );