2013-10-24 66 views
0

我需要javascript中的sendAsBinary()函数,但似乎Chrome本身已将其删除。在Mozilla的MDN(https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest),它们提供延伸了XMLHttpRequest原型的自定义函数:Chrome中的XML XMLHttpRequest.sendAsBinary()支持

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()消息。

+0

无法重现。按照您的指定,所有后续的新XMLHttpRequest对象都有一个'sendAsBinary'方法。铬30 – Brian

回答

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/