Javascript 如何使用php和ajax保存画布图像数据?
我在vps上遵循了本教程: testSave.phpJavascript 如何使用php和ajax保存画布图像数据?,javascript,php,jquery,ajax,html,Javascript,Php,Jquery,Ajax,Html,我在vps上遵循了本教程: 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
<?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);
}
函数saveViaAJAX()
{
var testCanvas=document.getElementById(“testCanvas”);
var canvasData=testCanvas.toDataURL(“image/png”);
var postData=“canvasData=”+canvasData;
var debugConsole=document.getElementById(“debugConsole”);
debugConsole.value=canvasData;
//警报(“canvasData=“+canvasData”);
var ajax=new-XMLHttpRequest();
open(“POST”,“testSave.php”,true);
setRequestHeader('Content-Type','canvas/upload');
//setRequestHeader('Content-TypeLength',postData.length);
ajax.onreadystatechange=function()
{
if(ajax.readyState==4)
{
//警报(ajax.responseText);
//写出文件名。
document.getElementById(“debugFilenameConsole”).innerHTML=“另存为重新加载此页面以生成新图像,或单击文件名以打开图像文件。”; } } 发送(postData); } 问题是,当用户单击“通过ajax发送”时,服务器目录()中没有发送/生成图像。结果是:目录中的所有内容都保持不变 应该在“另存为”下生成图像链接 有什么解决办法吗 p.S.
是否还有其他方法可以使用php来回传图像链接?问题在于您的AJAX。参考Url此处给出了使用php和ajax保存画布的代码。
很好的尝试,您的代码将覆盖文件而不是生成文件。谢谢你!