LoginSignup
3
5

More than 3 years have passed since last update.

nuxt.js × firebase で画像保存処理実装してみた

Last updated at Posted at 2020-07-28

使うもの

  • nuxt.js
  • firebase storage

今回実装するもの

  • ローカルフォルダから画像を選択してfirebaseのstorageに保存する処理
  • firebaseのstorageからデータを取得して画面上に表示する処理

コード

画像をfirebaseのstorageに保存

<!-- 画像を選択 -->
<input type="file" @change="selectIcon">
selectIcon (e) {
    // 選択した画像ファイルを取得
    const file = e.target.files[0]
    // refの中身が保存する場所のpathになる
    const storageRef = firebase.storage().ref('images/sample.jpg')
    storageRef.put(file)
}

firebaseのstorageからデータを取得して画面上に表示

<!-- ここに表示する -->
<img :src="icon">
data () {
    return {
        icon: ''
    }
},
methods: {
    async setIcon () {
        const storageRef = firebase.storage().ref()
        // childの中身にパスを指定してurlを取得する
        const url = await storageRef.child('images/sample.jpg').getDownloadURL()
        this.icon = url
    }
}

おまけ(画像選択してその場で表示する方法)

<img :src="icon">
<input type="file" @change="selectIcon">
data () {
    return {
        icon: ''
    }
},
methods: {
    selectIcon (e) {
        const file = e.target.files[0]
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (e) => {
            this.icon = e.target.result
        }
    }
}
3
5
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
3
5