xhr.responseType = 'blob';そしてデータを受信したら、それをもとにURLを生成して<img>タグのsrcに設定します。
document.querySelector("#img").src =
window.URL.createObjectURL(this.response);これでおしまい。信じられないくらいに簡単にイメージファイルをやりとりできます。ちなみに、参考例としてarraybufferを利用した場合の処理も挙げておきました。responseTypeをarraybufferにしておき、受信した後でちょっとした処理をします。var blob = new Blob([this.response], {type: 'image/jpg'});
document.querySelector("#img").src =
window.URL.createObjectURL(blob);ArrayBufferは、文字通りバイナリデータを扱うものです。ここでは、ArrayBufferからBlobオブジェクトを作成して利用しています。ArrayBufferからBlobへの変換はこのように簡単にできます。※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
※Blobによるイメージファイルの受信
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>タイトル</title>
<style>
h1 { font-size: 18pt; background: #AAAAEE; padding: 5px;}
</style>
<script type="text/javascript">
function doAction(e){
var xhr = new XMLHttpRequest();
xhr.open('GET', '/image.jpg', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
document.querySelector("#img").src =
window.URL.createObjectURL(this.response);
}
};
xhr.send();
}
</script>
</head>
<body>
<header>
<h1>XHR2 Sample</h1>
</header>
<article>
<p id="msg"></p>
<img id="img" src="" />
<button onclick="doAction();">Click</button>
</article>
</body>
</html>
※ArrayBufferを利用する場合
function doAction(e){
var xhr = new XMLHttpRequest();
xhr.open('GET', '/image.jpg', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'image/jpg'});
document.querySelector("#img").src =
window.URL.createObjectURL(blob);
}
};
xhr.send();
}
| << 前へ | 次へ >> |