遵循線上教學課程後,請嘗試將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中文網其他相關文章!