XMLHttp java服务端与 js客户端通讯实现二进制流收发

来源:互联网 发布:mac新版迅雷下载不了 编辑:程序博客网 时间:2024/06/06 13:16

XMLHttp  java服务端与 js客户端通讯实现二进制流收发

js客户端:

var xhr = cc.loader.getXMLHttpRequest();xhr.responseType = "arraybuffer";var that = this;xhr.onreadystatechange = function () {    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {       var binary = new Uint8Array(xhr.response);    }}xhr.open("POST", "http://192.168.199.88:8787");var str = "test=1&idLogin=10086";var buf = new ArrayBuffer(str.length); // 1 bytes for each charvar view = new Uint8Array(buf);for (var i=0, strLen=str.length; i<strLen; i++) {     view[i] = str.charCodeAt(i);}xhr.send(buf);


参考如下:http://blog.csdn.net/u011462674/article/details/9748359

利用XMLHttpRequest同步和异步下载二进制文件的解决方案。

在XMLHttpRequest里支持二进制数据的下载了,现分别以同步和异步两种方式分别介绍。

异步的方式下载:

[html] view plain copy
  1.   
[javascript] view plain copy
  1. xmlRequest.open("GET""0.jpg"true);  
  2. xmlRequest.responseType = "blob";//这里是关键,它指明返回的数据的类型是二进制  
  3. xmlRequest.onreadystatechange = function(e) {  
  4.     if (this.readyState == 4 && this.status == 200) {  
  5.         var response = this.response;  
  6.         img.src = window.URL.createObjectURL(response);  
  7.     }  
  8. }  
  9. xmlRequest.send(null);  

同步的方式下载:

[html] view plain copy
  1. <pre name="code" class="javascript">    xmlRequest.open("GET", "0.jpg", false);  
  2.     xmlRequest.overrideMimeType('text/plain; charset=x-user-defined');//这里是关键,不然 this.responseText;的长度不等于文件的长度  
  3.     xmlRequest.onreadystatechange = function(e) {  
  4.     if (this.readyState == 4 && this.status == 200) {  
  5.               var text = this.responseText;  
  6.               var length = text.length;  
  7.               var array = new Uint8Array(length);  
  8.               for (var i = 0; i < length; ++i) {  
  9.                   array[i] = text.charCodeAt(i);  
  10.               }  
  11.               var blob = new Blob([array], { "type": "image/jpeg" });  
  12.               img.src = window.URL.createObjectURL(blob);  
  13.           }  
  14.       }  
  15.     xmlRequest.send(null);</pre><br>  
  16. <pre></pre>  
  17. 注意:w3c标准中规定同步的情况下是不能设置responseType属性的。  
  18. <p></p>  
  19. <p></p>  
  20. <p></p>  
  21. <pre></pre>  
  22. <pre></pre>  
  23. <pre></pre>  
  24.     

0 0
原创粉丝点击