遵循在线教程后,尝试将 HTML5 Canvas 保存为图像在服务器上导致文件损坏或空。原因尚不清楚。
1.正确配置 XMLHttpRequest:
var xmlHttpReq = false; if (window.XMLHttpRequest) { ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { ajax = new ActiveXObject("Microsoft.XMLHTTP"); }
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
2.修改 PHP 脚本:
if ($fp) { fwrite($fp, $unencodedData); fclose($fp); }
JavaScript
function saveImage() { var canvasData = canvas.toDataURL("image/png"); var xmlHttpReq = false; if (window.XMLHttpRequest) { ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.open("POST", "testSave.php", false); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.onreadystatechange = function() { console.log(ajax.responseText); } ajax.send("imgData=" + canvasData); }
PHP
<?php if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) { $imageData = $GLOBALS['HTTP_RAW_POST_DATA']; $filteredData = substr($imageData, strpos($imageData, ",")+1); $unencodedData = base64_decode($filteredData); if ($fp = fopen('/path/to/file.png', 'wb')) { fwrite($fp, $unencodedData); fclose($fp); } } ?>
以上是为什么我的 HTML5 Canvas 图像保存到服务器时会损坏?的详细内容。更多信息请关注PHP中文网其他相关文章!