1
1

More than 3 years have passed since last update.

初めてのFirebaseを触ってみる(Storage)

Last updated at Posted at 2020-04-12

はじめに

おはようございます。こんにちは。こんばんは。
今回はFirebase Storageを解説していきます。
ではやっていきます。
※今回もwebベース(Vue.js)の解説です。
https://firebase.google.com/docs/storage?hl=ja

Firebase Storage(Cloud Storage)

Firebaseが提供している機能の一つで、写真や動画など、ユーザーが作成したコンテンツを保管、提供する必要のあるアプリ デベロッパー向けに構築されています。

画像をStorageにアップロードする。

時を戻そう・・・

Authenticationのところでユーザーのアカウントを設定できるがこの知識がいると説明したので
合わせてアイコン設定もやっていきましょう。
全て込み込みのコードです(コメント付き)。


<template>
    <div class="icon">  
        <img :src="this.uploadedImage" width="150" height="150" alt="" />
    </div>
    <input type="file" class="file_input" id="corporation_file" mulitple="multiple" @change="onDrop">
    <div class="preview">  
        <img :src="this.settingImage" width="50" height="50" alt="" />
    </div>
    <input type="button" value="編集" @click="update">
</template>

<script>
import firebase from '@/plugins/firebase'

export default {
    dara() {
      fileList: "",
      uploadedImage: "",
      settingImage: "",
      isDropingFlg: false //ドロップ判定
    },
    mounted() {
      firebase.auth().onAuthStateChanged((user)=> {
          if (user != null) {
            if(user.photoURL != null) {
              this.uploadedImage = user.photoURL;
            }
          }
      })
    },
    methods: {
        onDrop(event){
            this.isDropingFlg = true;
            //画像データ取得
            let fileList = event.target.files || e.dataTransfer.files;
            this.fileList = fileList;

            this.createImage(fileList[0]);
        },
        // アップロードした画像を表示
        createImage(file) {
            let reader = new FileReader();
            reader.onload = (e) => {
                this.settingImage = e.target.result;
            };
            reader.readAsDataURL(file);
        },
        update() {
          if(this.isDropingFlg) {
                //ドロップした画像の種類の判定
                var errFlg;
                if(this.fileList[0].type == "image/png") {
                    var blob = new Blob(this.fileList, { type: "image/png" });
                    errFlg = false;
                } else if(this.fileList[0].type == "image/jpg") {
                    var blob = new Blob(this.fileList, { type: "image/jpg" });
                    errFlg = false;
                } else if(this.fileList[0].type == "image/jpeg") {
                    var blob = new Blob(this.fileList, { type: "image/jpeg" });
                    errFlg = false;
                } else if(this.fileList[0].type == "image/gif") {
                    var blob = new Blob(this.fileList, { type: "image/gif" });
                    errFlg = false;
                } else {
                    errFlg = true;
                }

                if(!errFlg) {
                    this.updateImage(blob);
                }
            }
          },
          updateImage(blob) {
              var storageRef = firebase.storage().ref();
              var mountainsRef = storageRef.child(this.fileList[0].name);
              //Firebase 画像アップロード
              mountainsRef.put(blob).then(snapshot => {
                  //アップロード完了
                  mountainsRef.getDownloadURL().then((url) => {
                      //アップロードした画像の保存場所のURLを取得する
                      this.updateAccount(url);
                  }).catch((error) => {
                      console.log(error);
                  });
              });
          },
          updateAccount(url) {
            var user = firebase.auth().currentUser;
            user.updateProfile({
                photoURL: url
            }).then((user) => {
                alert("アカウントを編集しました");
            }).catch((error) => {
                alert("予期せぬエラーが起こりました");
            });
          }
      }
}

getDownloadURL()で画像のフルパスを入手し、アイコンに設定している

リサイズについてはCloud Functionsを使いますのでその時にできればと考えています。

以上。
解説が浅いところとか、間違い等があれば教えてください。
次回はfirebase Functionsを解説していきます。
最後まで読んでいただきありがとうございました。

Twitterやってます。良ければチェックして見てください。:point_up::point_up::point_up:

リンク

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