torstai 25. marraskuuta 2010

sendAsBinary for Google Chrome

The Firefox implementation of XMLHttpRequest has a convenience feature for sending binary data to a server using HTTP POST. The binary data is passed to a method called sendAsBinary as a string with meaningless upper bytes. Javascript has 16-bit strings, so when used to represent binaries each characters has 8 extra bits. A bug had been filed against Google Chrome not having such a method.

I spent some time this evening writing the code that adds a similar method to XHR of Google Chrome, but my implementation should theoretically work with any browser that implements the latest web standards. I did not spend much time testing the code, so it might have bugs in it. It probably is not the most efficient way either. I am just publishing it here in spirit of release early release often.

XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
var bb = new BlobBuilder();
var data = new ArrayBuffer(1);
var ui8a = new Uint8Array(data, 0);
for (var i in datastr) {
if (datastr.hasOwnProperty(i)) {
var chr = datastr[i];
var charcode = chr.charCodeAt(0)
var lowbyte = (charcode & 0xff)
ui8a[0] = lowbyte;
bb.append(data);
}
}
var blob = bb.getBlob();
this.send(blob);
}