2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue.js】Firebase Cloud Storage にファイルをアップロードする方法

Last updated at Posted at 2020-09-01

#前提条件
・Vue.jsのプロジェクトファイルを作成している
・Vuetify.jsの導入ができている
・Firebaseとの接続ができている

#実装方法
1、file形式で画像をアップロードする
2、変更があった場合は、@changeで感知して、onFilePickedを実行
3、Cloud Storageにアップロードする
4、アップロードしたファイルのURLをFirestoreに保存する

template


<template>
  <div>
    <img :src="imageUrl" height="150" v-if="imageUrl" />
    <v-file-input
      type="file"
      show-size
      ref="fileupload"
      accept="image/png, image/jpeg, image/bmp"
      prepend-icon="mdi-camera"
      label="UPLOAD IMAGE"
      @change="onFilePicked"
    ></v-file-input>

    <v-btn @click="upload">アップロード</v-btn>
  </div>
</template>

##script

<script>
import firebase from 'firebase'

export default {
  data () {
    return {
      imageName: "",
      imageUrl: "",
      imageFile: "",
    };
  },
  methods: {
    onFilePicked (file) {
      if (file !== undefined) {
        this.imageName = file.name;
        if (this.imageName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(file);
        fr.addEventListener("load", () => {
          this.imageUrl = fr.result;
          this.imageFile = file;
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
        this.$refs.fileupload.value = null;
      }
    },

    // 画像アップロード処理
    upload: function () {
     firebase.storage().ref().child(`images/${this.imageName}`).put(this.imageFile).then(snapshot => {
        snapshot.ref.getDownloadURL().then(downloadURL => {
          firebase.firestore().collection("images").add({
            downloadURL,
          });
        });
      });

      this.imageName = "";
      this.imageFile = "";
      this.imageUrl = "";
      this.$refs.fileupload.value = null;
    }
  },
};
</script>

#Thanks
【Nuxt.js × Vuetify】ファイル入力情報を受け取る
How to reset/clear file Input

2
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?