1. ajax请求服务器二进制文件的方法。
//二进制Ajax请求 var xmlhttpbinary; //获得请求url的参数 function GetRequest() { //向服务器发送异步请求 xmlhttpbinary = null; if (window.XMLHttpRequest) {// code for IE7, Firefox, Opera, etc. xmlhttpbinary = new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE6, IE5 xmlhttpbinary = new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttpbinary != null) { xmlhttpbinary.responseType = "blob"; //这里要用blob xmlhttpbinary.onreadystatechange = blobxpr_state_Change; xmlhttpbinary.open("GET", "test3.txt", true); xmlhttpbinary.send(null); } else { alert("Your browser does not support XMLHTTP."); } }
注释:xmlhttpbinary的请求类型应该是blob
2. 接收返回的数据
function blobxpr_state_Change() { if (xmlhttpbinary.readyState == 4) {// 4 = "loaded" if (xmlhttpbinary.status == 200) {// 200 = "OK" var bigblob = xmlhttpbinary.response; var reader = new FileReader(); var smallblob; smallblob = bigblob.slice(0, 22); reader.readAsArrayBuffer(smallblob); reader.onloadend = function (evt) { //filereader加载blob成功处理函数 var buffer = evt.target.result; //读取int var dv = new DataView(buffer); var a5 = dv.getInt32(0); //读取string var enc = new TextDecoder(); var abc = enc.decode(buffer); alert("获得字符串 " + abc); document.getElementById("demo").innerhtml = abc; } } else { alert("Problem retrieving XML data:" + xmlhttpbinary.statusText); } } }
注释,转int时用DataView.getInt32()函数,注意用C#转int至byte[]的顺序与getInt32()函数的顺序相反。87,100,0,0 0,0,100,87,需要注意下。C#写二进制文件时,结尾会有3个byte的莫名字符,decode()的时候需要将这3个字符去掉。