2012-05-04 12 views
1

我有一个highcharts svg,我通过canvg转换为png并显示在网页上。然后我想将这个PNG发送到服务器以创建一个图像链接。我下面的答案代码另一个话题:将服务器上的Canvas另存为图像时出现setRequestHeader错误

Renaming an image created from an HTML5 canvas

我的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”这一行发出以下错误:

Component returned failure code: 0x804b000f (NS_ERROR_IN_PROGRESS) [nsIXMLHttpRequest.setRequestHeader] http://whichchart.com/oil.js Line 102

在铬上同一行中的错误是:

Uncaught Error: INVALID_STATE_ERR: DOM Exception 11 saveDataURLoil.js:106 (anonymous function)

的例子可以在这里看到:whichchart.com。你能帮我吗?谢谢。

回答

1

好吧,所以我在搜索后发现了一个不同的解决方案。链接是在这里:

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); 
} 
?> 
相关问题