简体   繁体   English

有什么方法可以使用XMLHttpRequest对象发送二进制数据吗?

[英]Is there any way to send binary data with XMLHttpRequest object?

I'am trying to send binary chunk with XMLHttpRequest 我正在尝试使用XMLHttpRequest发送二进制块

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

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

xhr.send(bindata);

But this approach not works. 但是这种方法行不通。 I've tried to provide Content-type: application/octet-stream , Content-encoding headers for xhr and they don't work either. 我尝试提供Content-type:application / octet-streamxhr的 Content-encoding标头,它们也不起作用。 I am suspect that there is no way to compose request of such kind. 我怀疑无法撰写此类请求。

I would appreciate any help. 我将不胜感激任何帮助。

XMLHttpRequest.sendAsBinary is obsolete. XMLHttpRequest.sendAsBinary已过时。 Link 链接

As MDN mentioned , you can directly send binary typed array: MDN所述 ,您可以直接发送二进制类型的数组:

var myArray = new ArrayBuffer(512);
var longInt8View = new Uint8Array(myArray);

// generate some data
for (var i=0; i< longInt8View.length; i++) {
  longInt8View[i] = i % 256;
}

var xhr = new XMLHttpRequest;
xhr.open("POST", url, false);
xhr.send(myArray);

Yes you can send binary data using XHR. 是的,您可以使用XHR发送二进制数据。 All you need to do is set the appropriate headers and mime-type, and call the sendAsBinary method instead of the simple send method. 您需要做的就是设置适当的标头和mime-type,然后调用sendAsBinary方法而不是简单的send方法。 For example: 例如:

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

W3C has introduced Blob type to XMLHttpRequest in the latest specification . W3C在最新规范中将Blob类型引入到XMLHttpRequest中。 Currently I haven't seen any implementation so far but in near future this is definitely the way to download and upload binary data with XMLHttpRequest. 当前,到目前为止,我还没有看到任何实现,但是在不久的将来,这绝对是使用XMLHttpRequest下载和上传二进制数据的方法。

“处理二进制数据”一节在这里介绍了如何发送和通过XMLHttpRequest接收二进制数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM