Sending and Receiving Binary Data

responseType属性可以设置server返回字节的解析类型.比如"arraybuffer", “blob”, “document”, “json”, and “text”,对应的返回的类型就是ArrayBuffer, Blob, Document, JSON, or string

arraybuffer

使用arraybuffer接收png图片,并使用8bit unsigned integer array处理 raw bytes.只是处理字节,并没有解码图片,解码图片需要png decoding library

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++) {
      // do something with each byte in the array
    }
  }
};

oReq.send(null);

blob

使用Blob来读取binary file

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


var filestream = load_binary_resource(url);
var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)

参考:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
https://www.cnblogs.com/litao229/archive/2012/09/10/2679105.html

发布了1794 篇原创文章 · 获赞 582 · 访问量 154万+

猜你喜欢

转载自blog.csdn.net/claroja/article/details/104292247
今日推荐