现在,我正在编写一个基于带有XHR2支持的promise的AJAX库的新版本(https://github.com/pyrsmk/qwest)。我目前正在编写单元测试,95%的库现在是健壮的。无论如何,我需要验证我们是否可以成功检索ArrayBuffer(XHR2支持"ArrayBuffer"响应类型),但我如何用PHP生成这个ArrayBuff?我使用什么协议?Base64?
我真的不知道该怎么处理这整件事。。。
EDIT:似乎当我向PHP发送ArrayBuffer时,数据由$_POST变量直接处理
简介
好吧,你不会发送一个";ArrayBuffer";。您发送的是数据,并指定一种格式来理解这些数据。然后,客户可以选择最好的方式来解释它
因此,ArrayBuffer只是一个用于数据(二进制数据)的通用固定长度容器,它使您能够创建";视图";使用JavaScript类型数组的底层数据。最酷的是,可以从一个ArrayBuffer源创建多个视图。
也就是说,在您的特定情况下,您可以用PHP发送二进制数据,就像用PHP发送任何数据一样。
示例:
服务器.php
$filename = 'img.png';
$fsize = filesize($filename);
$handle = fopen($filename, "rb");
$contents = fread($handle, $fsize);
fclose($handle);
header('content-type: image/png');
header('Content-Length: ' . $fsize);
echo $contents;
或更短的
$filename = 'img.png';
header('content-type: image/png');
header('Content-Length: ' . filesize($filename));
readfile($filename);
client.js
var xhr = new XMLHttpRequest();
xhr.open('GET', 'server.php', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
console.log(uInt8Array);
};
xhr.send();
在php中处理二进制数据有点棘手。若要响应ArrayBuffer,必须将其强制转换为二进制字符串,并使用echo语句生成结果。
要从8位数组生成二进制字符串,必须使用pack语句。如果服务器不支持PHP 5.6+版本,则可以转换每个数组项并使用点运算符进行连接:
server.php
<?php
header('content-type: application/octet-stream');
$arrayBuffer = array(0, 1, 2, 253, 254, 255);
$binary = "";
for($index = 0; $index < count($arrayBuffer); $index++)
{
$binary = $binary.pack("C*", $arrayBuffer[$index]);
}
echo $binary;
?>
原始数据的MIME类型为应用程序/八位字节流。在客户端的JavaScript代码看起来像:
client.js
let xmlRequest = new XMLHttpRequest();
xmlRequest.open('POST', 'server.php');
xmlRequest.responseType = 'arraybuffer';
xmlRequest.onload = event =>
{
let arrayBuffer = new Uint8Array(event.target.response);
console.log('arrayBuffer: ', arrayBuffer); // [0, 1, 2, 253, 254, 255];
};
xmlRequest.send();