我写了一个片段,其中使用ajax和php保存图像。
这是代码,
的Ajax:
$jq("#up").click(function() {
var canvasData = upcan.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testsave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
});
此处是单击的按钮。 canvasData具有图像格式的画布上下文数据。
腓:
<?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;
$random_digit=rand(0000,9999);
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'canvas/canvas'.$random_digit.'.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
图像保存成功。现在我想在ajax中获取已保存图像的名称,以便我可以将其保存在变量中并进一步使用。那我怎么能这样做呢?
答案 0 :(得分:2)
// js
ajax.onreadystatechange = function() {
alert(ajax.responseText);
}
// php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
//...
echo 'canvas/canvas'.$random_digit.'.png';
}
但在我看来,最好使用jQuery ajax及其事件。