后端输出二进制数据,前端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>
相关推荐
2601_958492552 小时前
Optimizing Engagement with Freehead Skate - HTML5 Game - Construct 3
前端·html·html5
茉莉玫瑰花茶2 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
zhangxingchao3 小时前
AI应用开发六:企业知识库
前端·人工智能·后端
山峰哥4 小时前
SQL慢查询调优实战:从全表扫描到索引覆盖的完整复盘
前端·数据库·sql·性能优化
红尘散仙4 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
moshuying4 小时前
AI Coding 最大的 token 黑洞,可能根本不是 prompt
前端
红尘散仙4 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
lichenyang4534 小时前
HarmonyOS HMRouter 接入记录:从普通 Tab Demo 到路由跳转
前端
木斯佳5 小时前
前端八股文面经大全:腾讯WXG暑期前端一面(2026-05-15)·面经深度解析
前端·面试·笔试