0

我写了一个片段,其中使用 ajax 和 php 保存图像。

这是代码,

阿贾克斯:

$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:

<?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 中获取已保存图像的名称,以便我可以将其保存在变量中并进一步使用它。那么我该怎么做呢?

4

1 回答 1

2
// js

ajax.onreadystatechange = function() {
    alert(ajax.responseText);
}


// php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
     //...
     echo 'canvas/canvas'.$random_digit.'.png';
}

但在我看来,最好使用 jQuery ajax 及其事件。

于 2012-09-12T12:10:30.617 回答