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

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值