0
0

More than 3 years have passed since last update.

firebase-cloudStorageでの画像のアップロード

Last updated at Posted at 2020-08-28

firebase-cloudStorageを使って画像の管理をしようと思い
ドキュメントをみてやってみたけどうまくいかなかった。
自分の見方が悪かった。。。

修正後

<template>
  <div id="images">
    <input type="file" accept=”image/*” @change="selectImage" value="画像追加" />
    <button @click="upLoad">画像追加</button>
  </div>
</template>
<script>
import firebase from "../plugins/firebase";

export default {
  name: "images",
  data() {
    return {
      storage: firebase.storage(),
      image: "",
    };
  },
  methods: {
    selectImage(e) {
      e.preventDefault();
      this.image = e.target.files[0];
    },
    upLoad() {
      const storageRef = this.storage.ref().child(`images/${this.image.name}`);
      storageRef
        .put(this.image)//保存するファイル
        .then((snapshot) => {
          console.log("完了");
        })
        .catch(() => {
          console.log("エラー");
        });
    },
  },
};
</script>

原因

upLoad() {
      const storageRef = this.storage.ref().child(`images/${this.image.name}`);//ここ
      storageRef
        .put(this.image)
        .then((snapshot) => {
          console.log("完了");
        })
        .catch(() => {
          console.log("エラー");
        });
    },

const storageRef = this.storage.ref().child(images/${this.image.name});
の部分の.childの部分をフォルダ名だけ指定したらいいと思っていて
.child('images')としていたのが原因でした。
調べてみるとフォルダ名と保存するファイル名が必要だったみたいです。
.child()の部分が保存場所ってことですね

画像のURLの取得

 methods: {
    selectImage(e) {
      e.preventDefault();
      this.image = e.target.files[0];
    },
    upLoad() {
      const storageRef = this.storage.ref().child(`images/${this.image.name}`);
      storageRef
        .put(this.image)
        .then(() => {
          storageRef.getDownloadURL()//ここを追加
          .then((url) => {
            console.log(url);//ここに画像のURL
          });
          console.log("完了");
        })
        .catch(() => {
          console.log("エラー");
        });
    },
  },

これで画像のURLも取得できるのでこれをfirestoreとかに保存したりしたら使えそうです。

無事解決!

0
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
0
0