項目做到一個裁切圖片的功能,就是讓用戶上傳頭像的時候可以裁切一下圖片,選擇一個合適大小位置來作為頭像。之中用到了crop.js這個插件,用canvas直接繪制了用戶裁切縮放後的圖片。裁切的過程這邊就不詳細展開了,想要了解詳情的朋友可以深入了解一下crop.js插件,這邊分享一下在生成canvas圖片後,通過ajax來上傳到服務器的一個過程。就以PHP為例:
<script>
var canvas = document.getElementById("canvas_img");
var img = canvas.toDataURL();
var ajax = null;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
alert(ajax.responseText);
}
}
ajax.open("POST", "save.php", true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("img=" + img);
</script>
<?php
define('UPLOAD_DIR', dirname(__FILE__).'/'); //圖片保存路徑
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$day = date("Ymd",time());
$file_name = mt_rand(1000000000000000,9999999999999999);
if(!is_dir(UPLOAD_DIR . $day)){
mkdir(UPLOAD_DIR . $day);
}
$file = UPLOAD_DIR . $day."/".$file_name. '.png';
$success = file_put_contents($file, $data);
return $success;
?>
通過ajax傳輸的方式,讓服務器收到這整個圖片文件的內容,然後寫進文件裡,就有了我們所謂的‘上傳圖片’的效果了。