在这里,我正在编写基于 XHR2 支持的 promise 的新版本 AJAX 库 ( https://github.com/pyrsmk/qwest )。我目前正在编写单元测试,该库 95% 的内容现在都很健壮。无论如何,我需要验证我们是否可以成功检索 ArrayBuffer(XHR2 支持“arraybuffer”响应类型),但是如何使用 PHP 生成这个 ArrayBuffer?我使用什么协议(protocol)? Base64?
我真的不知道该如何处理整个事情......
编辑:似乎当我将 ArrayBuffer 发送到 PHP 时,数据直接由 $_POST 变量处理
最佳答案
简介
好吧,你不发送“ArrayBuffer”。您发送的是数据并指定一种格式来理解该数据。然后,客户可以选择最佳的解释方式。
因此,ArrayBuffer 只是数据(二进制数据)的通用固定长度容器,它使您能够使用 JavaScript 类型数组创建基础数据的“ View ”。最酷的事情是可以从单个 ArrayBuffer 源创建多个 View 。
话虽这么说,在您的具体情况下,您可以像在 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();
关于javascript - 通过 JavaScript XHR2 对象在 PHP 中发送 ArrayBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26764192/