Skip to content

Instantly share code, notes, and snippets.

@nnabeyang
Created December 28, 2012 09:56
Show Gist options
  • Select an option

  • Save nnabeyang/4396528 to your computer and use it in GitHub Desktop.

Select an option

Save nnabeyang/4396528 to your computer and use it in GitHub Desktop.
xhr2でバイナリデータを送信するの続編。今回はBlobで送ります。ArrayBufferはおそらくサイズを途中で伸ばしたり、縮めたりできないので、インプットの大きさが分からない場合はBlobを使って送ればできるようです。サーバー側は https://gist.github.com/4394635 を参照してください。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>xhr2 test</title>
<body>
<input type="text" id="input"/>
<button id="send">send</button>
<script>
var inputEL = document.getElementById('input');
document.getElementById('send').addEventListener('click', function(e) {
var inputs = inputEL.value.split(',');
if(isNaN(parseInt(inputs[0]))) return;
var bufs = [];
var v, buf;
for(var i = 0; v = inputs[i]; i++) {
buf = new ArrayBuffer(1);
dv = new DataView(buf);
dv.setUint8(0, parseInt(v));
bufs.push(buf);
}
var views = [];
for(var i = 0; bufs[i]; i++) {
views.push(new Uint8Array(bufs[i]));
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/send', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var dv;
if(this.status == 200) {
var txtArea = document.createElement('textarea');
var dv = new DataView(this.response);
var txt = '(';
var size = this.response.byteLength;
for(var i = 0; i < size; i++) {
txt += dv.getUint8(i)
if(i == size - 1) txt += ')';
else txt += ',';
}
txtArea.value = txt;
document.body.appendChild(txtArea);
} else {
console.log(this.status);
}
};
xhr.send(new Blob(views, {type: 'application/octet-stream'}));
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment