LoginSignup
2
0

More than 3 years have passed since last update.

fetch APIによる画像の取得とData URIの発行

Posted at

内容

POST通信しながら画像をイメージタグに入れる方法がないかと探してたけど、上手くまとまっているものが見当たらんかったので、備忘録。通信後にレスポンス結果をバイナリデータとし、それに対してData URI(webブラウザ上に領域を確保した際の仮のURI?)を発行し、これをタグのsrcに設定する。

仮に以下のようなhtmlがあったとする。

<img class="image"></img>

そしたら以下のような感じ。


fetch(url, {
  method: "POST",# GET, POST
  mode: "cors", // no-cors, cors, *same-origin
  cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
  credentials: "same-origin", // include, same-origin, *omit
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    "hoge":"hoge" // post時の引数
  })
  }).then(respons => {
     return respons.blob(); // バイナリデータとする?
  }).then(blob =>{
     return URL.createObjectURL(blob); // Data URI発行
  }).then(dataUri =>{
     $('.image').attr('src', dataUri);
  })
});
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0