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

認可付きAPIから画像を取得してVueで表示する

やりたいこと

axiosで、認証付き画像を取得し、<img>で表示する

問題

認証付きAPIが画像を返してくれるが、バイナリデータがそのまま来るためsrcで指定できない。困る。

解決

その1 base64で文字列にして読み込む

  • responseType: "arraybuffer"を指定する
ImageFromApi.vue
<template>
  <img :src="dataUrl" />
</template>

<script>
import axios from "axios";

export default {
  name: "ImageFromApi",
  props: {
    apiUrl: {
      type: String,
      required: true
    }
  },
  data: function() {
    return {
      dataUrl: ""
    };
  },
  mounted() {
    axios
      .get(this.apiUrl, {
        responseType: "arraybuffer",
        headers: {
          Authorization:
            "Bearer " + <Tokenを入れる>
        }
      })
      .then(response => {
        const prefix = `data:${response.headers["content-type"]};base64,`;
        const base64 = new Buffer(response.data, "binary").toString("base64");
        this.dataUrl = prefix + base64;
      });
  }
};
</script>

その2 blobObjectURLを生成して読み込む

  • responseType: "blob"を指定する
ImageFromApi.vue
<template>
  <img :src="blobUrl" />
</template>

<script>
import axios from "axios";

export default {
  name: "ImageFromApi",
  props: {
    apiUrl: {
      type: String,
      required: true
    }
  },
  data: function() {
    return {
      blobUrl: ""
    };
  },
  mounted() {
    axios
      .get(this.apiUrl, {
        responseType: "blob",
        headers: {
          Authorization:
            "Bearer " + <Tokenを入れる>
        }
      })
      .then(response => {
        this.blobUrl = window.URL.createObjectURL(response.data);
      });
  }
};
</script>

結論

画像を表示するたびにbase64が走り、重い画像がさらに重くなるので、
その2 `blob`で`ObjectURL`を生成して読み込むを採用とする。

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
ユーザーは見つかりませんでした