4

I'm trying to post binary data to a server. This works exactly as I need it, in Chrome 15:

XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
    function byteValue(x) {
        return x.charCodeAt(0) & 0xff;
    }
    var ords = Array.prototype.map.call(datastr, byteValue);
    var ui8a = new Int8Array(ords);
    this.send(ui8a.buffer);
};

However, I need this to work in certain browsers that don't support the Int8Array type (or Blobs).

Maybe the solution is to create my own implementation of ArrayBuffer (ui8a.buffer is an ArrayBuffer). The problem is, I don't know what this object is; examining it on the JavaScript console shows only a byteLength property.

Update: I feel like I'm getting close but my conversion isn't correct. Here's what I'm trying:

XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
    var blob;
    function byteValue(x) {
        return x.charCodeAt(0) & 0xff;
    }
    var ords = Array.prototype.map.call(datastr, byteValue);
    if (window.Int8Array) {
        var ui8a = new Int8Array(ords);
        blob = ui8a.buffer;
    } else {
        var strArray = Array.prototype.map.call(ords, function(x) {
            if (x > 127) x = x-256;
            return String.fromCharCode(x); 
        }); 
        blob = strArray.join();
    }
    this.send(blob);
};

My blob ends up being double the length it should be -- which hints at your mention of encoding two bytes at a time. But I'm not really sure how to do that (yet)...

wildabeast
  • 1,723
  • 3
  • 18
  • 31
  • 1
    If you want to send binary data using XHR, you'll need to encode the binary data in a string. You can use the `String.fromCharCode` method to do so. Remember that characters in JavaScript are 2 bytes long. Hence you'll need to encode 2 bytes at a time. In addition, when using XHR you'll also need to specify the `Content-length` header so that the server knows when the binary data comes to an end. I'll create a `BitArray` constructor in JavaScript to ease development, but I'm a little busy just now so it'll take come time. Until then try experimenting for yourself. Cheers. Happy coding. =) ;) – Aadit M Shah Nov 17 '11 at 04:32
  • Thanks Aadit -- I updated my post with my progress, but I'm still not quite there... – wildabeast Nov 18 '11 at 00:15

0 Answers0