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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4376657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:13:16  来源:igfitidea点击:

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

javascriptbinaryxmlhttprequestsend

提问by duganets

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-encodingheaders for xhrand they don't work either. I am suspect that there is no way to compose request of such kind.

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

I would appreciate any help.

我将不胜感激任何帮助。

回答by Bo Lu

XMLHttpRequest.sendAsBinaryis obsolete. Link

XMLHttpRequest.sendAsBinary已过时。关联

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);

回答by Aadit Shah

Yes you can send binary data using 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. For example:

是的,您可以使用 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);

回答by Samuel Zhang

W3C has introduced Blob type to XMLHttpRequest in the latest specification. 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.

W3C 在最新的规范中为 XMLHttpRequest 引入了 Blob 类型。目前我还没有看到任何实现,但在不久的将来,这绝对是使用 XMLHttpRequest 下载和上传二进制数据的方式。

回答by Averius

The section "Handling binary data" heredescribes how to send and receive binary data via XMLHttpRequest.

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