3

I'am trying to send binary chunk with 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. I am suspect that there is no way to compose request of such kind.

I would appreciate any help.

Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
duganets
  • 1,853
  • 5
  • 20
  • 31
  • 1
    Are you trying to send a file this way? There are some changes in the level 2 spec that allow blob sending, it depends exactly what you're trying to do though: http://www.w3.org/TR/XMLHttpRequest2/#the-send-method – Nick Craver Dec 07 '10 at 12:41
  • No, this is not a file. It's a encoded packet that is supposed to be sent on server. Server, in its turn, responds with packet of similar structure. I understand I can do either way and encode/decode packets when sending/receiving being done with base64, but I try to save CPU time and packet size overhead because of webapp "realtimeness". – duganets Dec 07 '10 at 13:15

4 Answers4

4

XMLHttpRequest.sendAsBinary is obsolete. Link

As MDN mentioned, you can directly send binary typed array:

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);
Bo Lu
  • 687
  • 9
  • 11
1

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:

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

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.

Samuel Zhang
  • 1,290
  • 8
  • 14
0

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

Averius
  • 165
  • 1
  • 2
  • 13