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

4 kommenttia:

  1. As I implied, my code is in no way optimal. Feel free to post improved versions as comments.

    VastaaPoista
  2. For info on BlobBuilder see http://www.w3.org/TR/file-writer-api/#idl-def-BlobBuilder

    ...and for info on ArrayBuffer see https://cvs.khronos.org/svn/repos/registry/trunk/public/webgl/doc/spec/TypedArray-spec.html

    VastaaPoista
  3. Here are the Mozilla pages defining the method:
    https://developer.mozilla.org/en/XMLHttpRequest#sendAsBinary()
    https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Sending_binary_data

    And this is the original bug report for Chrome
    http://code.google.com/p/chromium/issues/detail?id=35705

    VastaaPoista
  4. It turns out Blogger does not support code in comments. I have moved development of the function to http://javascript0.org/wiki/Portable_sendAsBinary

    VastaaPoista