blob,後端生成圖片,前端如何使用?
阿新 • • 發佈:2019-01-03
後端生成圖片,前端通過http獲取
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>後端生成圖形驗證碼</title> </head> <body> <h1> 方式1、直接使用src屬性 <p> <img src="./api.php" alt="驗證碼"> </p> </h1> <h1> 方式2、http <p> <img alt="驗證碼" id="testImg"> </p> <script> const xhr = new XMLHttpRequest(); /* 這種情況,就需要使用blob型別的資料了 */ xhr.responseType = 'blob'; xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { /* 然後再使用 createObjectURL 方法可以獲取當前blob資源的url */ testImg.src = window.URL.createObjectURL(xhr.response); // 類似 blob:http://localhost/d2264025-c591-4518-9d0f-ddb86d671f96 } } xhr.open('post', './api.php'); xhr.send(); </script> </h1> </body> </html>
<?php
$img = imagecreatetruecolor(200, 200);
imagefilledrectangle($img, 0, 0, 200, 200, imagecolorallocate($img, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100)));
imagepng($img);
imagedestroy($img);
//$file = $_FILES['file'];
//echo json_encode($file);