Help us understand the problem. What is going on with this article?

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

内容

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);
  })
});
StrayDog
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした