Ajax发送和接收二进制字节流数据的方法
HTML5 Ajax 2.0标准中,增强了Ajax的许多功能,包括发送FormData数据,上传数据进度条等诸多功能。但实际上,Ajax可以字节发送二进制数据。
发送二进制数据
var oReq = new XMLHttpRequest(); oReq.open("POST", url, true); oReq.onload = function (oEvent) { // Uploaded. }; var blob = new Blob(['abc123'], {type: 'text/plain'}); oReq.send(blob);
或者
var myArray = new ArrayBuffer(512); var longInt8View = new Uint8Array(myArray); for (var i=0; i< longInt8View.length; i++) { longInt8View[i] = i % 255; } var xhr = new XMLHttpRequest; xhr.open("POST", url, false); xhr.send(myArray);
接收二进制数据
var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "arraybuffer"; oReq.onload = function (oEvent) { var arrayBuffer = oReq.response; // Note: not oReq.responseText if (arrayBuffer) { var byteArray = new Uint8Array(arrayBuffer); for (var i = 0; i < byteArray.byteLength; i++) { } } }; oReq.send(null);
当然,如上设置只能是文本类型,如果是Blob类型,那么如下即可
var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "arraybuffer"; oReq.onload = function(oEvent) { var blob = new Blob([oReq.response], {type: "image/png"}); // ... }; oReq.send();
或者
var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "blob"; oReq.onload = function(oEvent) { var blob = oReq.response; // ... }; oReq.send();
如果你使用的是旧版本的浏览器,那么加载二进制可以如下
function load_binary_resource(url) { var req = new XMLHttpRequest(); req.open('GET', url, false); //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com] req.overrideMimeType('text\/plain; charset=x-user-defined'); req.send(null); if (req.status != 200) return ''; return req.responseText; }
注意:x-user-defined告诉浏览器不要解析数据
相关推荐
chongxiaocheng 2020-08-16
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05