将画布另存为服务器上的图像时出现 setRequestHeader 错误


setRequestHeader Error When Saving Canvas as Image on Server

我有一个高图表svg,我已经通过canvg转换为png并显示在网页上。然后我想将此 png 发送到服务器以创建指向图像的链接。我正在关注另一个主题的答案代码:

重命名从 HTML5 画布创建的图像

我的JavaScript代码如下:

var timeout = window.setTimeout(function() {
    canvg(document.getElementById('canvas'), chart.getSVG());
}, 10000);
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("images/png");
document.write('<img src="'+img+'"/>');
saveDataURL(img)
function saveDataURL(canvas) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
            window.location.href = request.responseText;
        }
    };
    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    request.open("POST", "saveDataURL.php", true);
    request.send("dataURL=" + canvas.toDataURL());
}

我的 php 名为 saveDataURL.php 是:

$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL)[1];
$decodedData = base64_decode($encodedData);
file_put_contents("temp/faizan.png", $decodedData);
echo "http://whichchart.com/temp/faizan.png";

在 Firefox 12 中,在 "request.setRequestHeader" 行中会抛出以下错误:

组件返回的失败代码: 0x804b000f (NS_ERROR_IN_PROGRESS) [nsIXMLHttpRequest.setRequestHeader] http://whichchart.com/oil.js 102路

在 chrome 中,同一行上的错误是:

未捕获的错误: INVALID_STATE_ERR:DOM 异常 11 saveDataURLoil.js:106 (匿名功能)

可以在此处查看示例:whichchart.com。你能帮忙吗?谢谢。

好的,所以我在多次搜索后找到了不同的解决方案。链接在这里:

http://permadi.com/blog/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/

假设你有一个名为testCanvas的画布,这个javascript和php将起作用:

var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(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;
    // Save file.  This example uses a hard coded filename for testing,
    // but a real application can specify filename in POST variable
    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
}
?>
相关文章:
  • 没有找到相关文章