后端输出二进制数据,前端fetch接受二进制数据,并转化为字符输出

在PHP中,你可以将字符串或其他数据类型转换为二进制数据,并通过HTTP响应发送给前端。

php 复制代码
<?php
//设置正确的Content-Type头部,以便前端可以正确处理二进制数据
header('Content-Type:application/octet-stream');
$str ="hello world!";
$binaryData=hex2bin(bin2hex($str));
echo $binaryData;
?>

在这个前端代码中,我们使用fetch API请求PHP脚本,并获取二进制数据。然后,我们将ArrayBuffer转换为字符串,以便在JavaScript中使用。

javascript 复制代码
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
        <title>测试后端输出二进制,前端接收二进制并转化为字符</title>
    </head>
    <body>
        <script>
            fetch('fetchArraybuffer.php',{
                method:'get'
            })
            .then((response)=>{
                if(response.ok && response.status===200)
                {
                    return response.arrayBuffer();
                }
                throw new Error('返回数据出错');
            })
            .then((data)=>{
                const decoder=new TextDecoder('utf-8');
                const decodeStr=decoder.decode(data);
                console.log(decodeStr);  
            })
            .catch((error)=>{
                console.log('连接后端出错',error);
            });
        </script>
    </body>
</html>
相关推荐
岱宗夫up7 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
紫陌涵光8 小时前
112. 路径总和
java·前端·算法
漠月瑾-西安8 小时前
CVE-2025-55182漏洞解析:你的React项目安全吗?
前端·安全·react.js
No丶slovenly8 小时前
flutter笔记-输入框
前端·笔记·flutter
国产化创客9 小时前
ESP32+Web实现智能气象站
前端·物联网·智能家居·智能硬件
coderYYY10 小时前
VSCode终端启动报错
前端·ide·vscode·npm·编辑器
tod11310 小时前
Redis 数据类型与 C++ 客户端实践指南(redis-plus-plus)
前端·c++·redis·bootstrap·html
Sylvia33.10 小时前
火星数据:棒球数据API
java·前端·人工智能
weixin1997010801611 小时前
1688商品详情页前端性能优化实战
前端·性能优化
DEMO派11 小时前
前端常用XSS攻击演示与防御方案解析
前端·xss