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

18 篇文章 0 订阅

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 char
var 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里支持二进制数据的下载了,现分别以同步和异步两种方式分别介绍。

异步的方式下载:

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

同步的方式下载:

  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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VCHH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值