blob,后端生成图片,前端如何使用?

版权声明:任先阳 任 先 阳 任先 先阳,nvcc.cc、www.nvcc.cc、sbfox.com、www.sbfox.com https://blog.csdn.net/qq_39571197/article/details/85328233

后端生成图片,前端通过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);

猜你喜欢

转载自blog.csdn.net/qq_39571197/article/details/85328233