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