Justin
Justin

Reputation: 45360

Javascript XMLHttpRequest.sendAsBinary() support in Chrome

I need the sendAsBinary() function in javascript, but it seems that Chrome has removed it natively. On the Mozilla MDN (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), they provide a custom function which extends the XMLHttpRequest prototype:

if(!XMLHttpRequest.prototype.sendAsBinary) {
    XMLHttpRequest.prototype.sendAsBinary = function(sData) {
        console.log("calling sendAsBinary() method...");    
        var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
        for(var nIdx = 0; nIdx < nBytes; nIdx++) {
            ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
        }
        this.send(ui8Data);
    };
}

However, even though I implement the above, I am still getting:

Uncaught TypeError: Object #<XMLHttpRequest> has no method 'sendAsBinary' 

In Chrome 30.0.1599.101. I also never see my console.log() message.

Upvotes: 0

Views: 4146

Answers (1)

Alex
Alex

Reputation: 810

It seems that in Chrome you cannot use sendAsBinary but the FormData object and the send method. I assume you want to upload a file:

    var file = event.originalEvent.dataTransfer.files[0];
    var dashes = '--';
    var boundary = 'fuhtml5';
    var crlf = '\r\n';
    if (file.getAsBinary) { // Firefox
            var data = dashes + boundary + crlf +
                "Content-Disposition: form-data;" +
                "name=\"" + settings.name + "\";" +
                "filename=\"" + unescape(encodeURIComponent(file.name)) + "\"" + crlf +
                "Content-Type: application/octet-stream" + crlf + crlf +
                file.getAsBinary() + crlf +
                dashes + boundary + dashes;

            xmlHttpRequest.setRequestHeader("Content-Type", "multipart/form-data;boundary=" + boundary);
            xmlHttpRequest.sendAsBinary(data);

        } else if (window.FormData) { // Chrome

            var formData = new FormData();
            formData.append(settings.name, file);

            xmlHttpRequest.send(formData);

        }

This is not tested. It's extracted from the code at https://github.com/MicheleBertoli/jquery-html5-uploader/

Upvotes: 1

Related Questions