0

我需要sendAsBinary()javascript 中的函数,但 Chrome 似乎已将其删除。在 Mozilla MDN ( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest ) 上,他们提供了一个扩展 XMLHttpRequest 原型的自定义函数:

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

但是,即使我实现了上述内容,我仍然得到:

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

Chrome 30.0.1599.101. 我也从来没有看到我的console.log()消息。

4

1 回答 1

1

似乎在 Chrome 中您不能使用 sendAsBinary,而是使用 FormData 对象和 send 方法。我假设您要上传文件:

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

        }

这未经测试。它是从https://github.com/MicheleBertoli/jquery-html5-uploader/的代码中提取的

于 2014-09-14T14:10:54.550 回答