有没有办法用 XMLHttpRequest 对象发送二进制数据?

dug*_*ets 5 javascript binary xmlhttprequest send

我正在尝试使用 XMLHttpRequest 发送二进制块

var xhr = new XMLHttpRequest();
var bindata = 0x0f0f;

xhr.open("POST", "binary_reader.php");

xhr.send(bindata);
Run Code Online (Sandbox Code Playgroud)

但这种方法行不通。我尝试为xhr提供Content-type: application/octet-streamContent-encoding标头,但它们也不起作用。我怀疑没有办法提出这样的请求。

我将不胜感激任何帮助。

小智 1

是的,您可以使用 XHR 发送二进制数据。您需要做的就是设置适当的标头和 mime 类型,并调用 sendAsBinary 方法而不是简单的 send 方法。例如:

var req = new XMLHttpRequest();  
req.open("POST", url, true);  
// set headers and mime-type appropriately  
req.setRequestHeader("Content-Length", 741);  
req.sendAsBinary(aBody);
Run Code Online (Sandbox Code Playgroud)