文書の過去の版を表示しています。
−目次
11.Vue.jsとFirebaseで画像アップローダー
Vue.jsとFirebaseを用いて、画像アップローダーを作ってみたいと思います。
FirebaseのCloud Firestorageに複数の画像を保存します。しかし、直接その一覧をとってくることができないため、画像を保存する段階で、あらかじめ、Firestoreに画像のアドレスを保存しておく必要があるため、ややこしいコードになっています。
方針をたてる
- 画像をアップロードできる
- アップロードした画像の一覧が表示される
- 画像ファイルはFirebase Cloud Storageに保存
- 画像ファイルのアドレスはFirebase Firestoreに保存し、画像のアドレス一覧はそちらからとってくる
今回は、以下のコードを参考にさせていただきました。
https://medium.com/vue-mastery/full-stack-vue-js-with-firestore-62e2fe2ec1f3
ソースコード
https://codesandbox.io/embed/219m6n7z3j
0.用意するもの(開発環境)
パソコン Chrome(くろーむ、WEBブラウザの一つ) GitHubアカウント作成済み(無料) Googleアカウント作成済み(無料)
パソコンは、Windowsパソコンでも、Macでも、かまいませんが、私の場合はWindows 10 Proとなります。
今回利用するもの
CodeSandbox Firebase (Cloud Firestore, Cloud Storage) Vue 2.5.2 Vuetify firebase vuefire 2.0.0-alpha.6
新規Firebaseアプリの作成
09.emailとpasswordでパスワード制限と同様に、https://console.firebase.google.comから、Firebaseアプリを作成し、apiキーなどをメモ帳などに保存しておきます。
- var config以下の設定をコピーしておきます
- Database > Cloud Firestoreの、「データベースを作成」をクリック
- 一時的に、テストモードにしておきます
- 以下のような画面になります
- Storage > スタートガイド をクリック
- Storage の ルール をクリック
- 一時的に、以下のように変更して、「公開」をクリックします。(アップロード画像は500KB以下に制限)
なお、繰り返しになりますが、今回は、Realtime Databaseではなく、Cloud Firestoreを作成しています。
Codesandboxで新規Vue.jsアプリの作成
- CodeSandboxでVueアプリを新規作成
- Dependencyで、Vuetifyとfirebaseとvuefire 2.0.0-alpha.6を追加
- index.htmlとsrc/main.jsの編集し、Vuetifyとfirebaseを利用できるようにします。
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width,initial-scale=1.0" /> | |
<title>Vue Firebase Image Upload</title> | |
<link | |
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" | |
rel="stylesheet" | |
/> | |
</head> | |
<body> | |
<div id="app"></div> | |
<!-- built files will be auto injected --> | |
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase.js"></script> | |
<script> | |
// Initialize Firebase | |
// こちらにはご自身のFirebaseのAPIキーなどをコピペしてください | |
var config = { | |
apiKey: "<YOUR-API-KEY>", | |
authDomain: "xxxxx", | |
databaseURL: "xxxxx", | |
projectId: "xxxxx", | |
storageBucket: "xxxxx", | |
messagingSenderId: "xxxxx" | |
}; | |
firebase.initializeApp(config); | |
</script> | |
</body> | |
</html> |
<template> | |
<div id="app"> | |
<v-toolbar color="indigo" dark fixed app> | |
<v-toolbar-title>Vue Firebase Image Upload</v-toolbar-title> | |
</v-toolbar> | |
<v-app id="inspire"> | |
<v-content> | |
<v-container fluid> | |
<v-layout align-center justify-center> | |
<v-flex xs12 sm8 md4> | |
<v-card class="elevation-12"> | |
<v-text-field | |
label="Select Image" | |
@click="pickFile" | |
v-model="imageName" | |
prepend-icon="attach_file" | |
></v-text-field> | |
<input | |
type="file" | |
style="display: none" | |
ref="image" | |
accept="image/*" | |
@change="onFilePicked" | |
/> | |
<v-card-actions> | |
<v-spacer></v-spacer> | |
<v-btn color="primary" @click="upload">アップロード</v-btn> | |
</v-card-actions> | |
</v-card> | |
</v-flex> | |
</v-layout> | |
</v-container> | |
</v-content> | |
</v-app> | |
</div> | |
</template> | |
<script> | |
import { db } from "./main"; | |
export default { | |
name: "App", | |
data: { | |
photo: null, | |
photo_url: null, | |
dialog: false, | |
imageName: "", | |
imageUrl: "", | |
imageFile: "" | |
}, | |
methods: { | |
pickFile() { | |
this.$refs.image.click(); | |
}, | |
onFilePicked(e) { | |
const files = e.target.files; | |
if (files[0] !== undefined) { | |
this.imageName = files[0].name; | |
if (this.imageName.lastIndexOf(".") <= 0) { | |
return; | |
} | |
const fr = new FileReader(); | |
fr.readAsDataURL(files[0]); | |
fr.addEventListener("load", () => { | |
this.imageUrl = fr.result; | |
this.imageFile = files[0]; // this is an image file that can be sent to server... | |
}); | |
} else { | |
this.imageName = ""; | |
this.imageFile = ""; | |
this.imageUrl = ""; | |
} | |
}, | |
// 画像アップロード処理 | |
upload: function() { | |
var me = this; | |
// ストレージオブジェクト作成 | |
var storageRef = firebase.storage().ref(); | |
// ファイルのパスを設定 | |
var mountainsRef = storageRef.child(`images/${this.imageName}`); | |
// ファイルを適用してファイルアップロード開始 | |
mountainsRef.put(this.imageFile).then(snapshot => { | |
snapshot.ref.getDownloadURL().then(downloadURL => { | |
this.imageUrl = downloadURL; | |
db.collection("images").add({ downloadURL }); | |
}); | |
}); | |
} | |
}, | |
components: {} | |
}; | |
</script> | |
<style> | |
#app { | |
font-family: "Avenir", Helvetica, Arial, sans-serif; | |
-webkit-font-smoothing: antialiased; | |
-moz-osx-font-smoothing: grayscale; | |
text-align: center; | |
color: #2c3e50; | |
margin-top: 60px; | |
} | |
</style> |
// The Vue build version to load with the `import` command | |
// (runtime-only or standalone) has been set in webpack.base.conf with an alias. | |
import Vue from "vue"; | |
import App from "./App"; | |
import Vuetify from "vuetify"; | |
import "vuetify/dist/vuetify.css"; | |
import VueFire from "vuefire"; | |
import firebase from "firebase/app"; | |
import "firebase/firestore"; | |
Vue.use(VueFire); | |
Vue.use(Vuetify); | |
Vue.config.productionTip = false; | |
firebase.initializeApp({ | |
databaseURL: "xxxxx", | |
projectId: "xxxxx", | |
}); | |
export const db = firebase.firestore(); | |
/* eslint-disable no-new */ | |
new Vue({ | |
el: "#app", | |
components: { App }, | |
template: "<App/>" | |
}); |
src/App.vueの編集
初期データの設定
data: { photo: null, photo_url: null },
テンプレート
参考:
https://stackoverflow.com/questions/44989162/file-upload-in-vuetify
このように、画像ファイルはCloud Storageに保存され、画像ファイルのURLが、Firestoreに保存される。
Firebaseで画像アップロードのリンク
画像の一括ダウンロードが難しそう。
画像を保存するときに、画像のアドレスをdatabaseに保存しておき、一括ダウンロードのときに、そのアドレスを参照する必要があるらしい。
https://www.h-sakano.net/entry/2018/12/04/000000#Cloud-Storageへの画像の保存と表示
2018-12-04
Vue.jsにおけるFirebaseの主要な機能の取扱い
https://qiita.com/t_furu/items/ef99e9d48b9c3c9af7f1
@t_furu
2017年03月13日に更新
Firebase入門 - ファイル保存&管理機能を利用する
https://teratail.com/questions/126212
Firebase Storage 内のファイルのURLを一括で取得する方法
tarotarosu
投稿 2018/05/15 11:24
Vue.jsとFirebaseで画像アップロードのリンク
https://www.google.com/amp/s/luftgarden.work/tut-nuxt-dog-part1/amp/
Nuxt.js で簡単な画像一覧アプリを作成する – Part.1
https://press.monaca.io/atsushi/87
Monaca × Firebase連携 その1:Firebase Storage
2017年4月5日中津川篤司
→非常に分かりやすいです。
https://qiita.com/musatarosu/items/2a0f3915afbd9e717cff
https://qiita.com/rubytomato@github/items/11c7f3fcaf60f5ce3365
@rubytomato@github
2018年05月21日に更新
FirebaseのHostingとCloud Functionsを利用してStorageへファイルをアップロードするデモアプリケーション
https://kapi-travel.com/programing/firebase-cloud-storageへの画像アップロードアプリを実装/
Firebase Cloud Storageへの画像アップロードアプリを実装
2018.10.28
https://www.tohuandkonsome.site/entry/2018/01/18/222857
2018-01-18
ファイルアップロード機能で学ぶVue.js(1)
FirestoreからURLリストをダウンロード
まず、imageのURLを配列にしたものをconsoleに表示するところまではできたのだが、どうしてもそれをtemplate内に表示させることがてきなかった。
mountedを用いる?
https://tech.mof-mof.co.jp/blog/vue-firestore-ramens.html
Vue.js + Firestoreでデータを取得してラーメン一覧を表示する
https://firebase.google.com/docs/firestore/query-data/get-data?hl=ja
Firebase Realtime Databaseでは、自動で付与されるIDが日付順になっていたのだが、Firestoreでは日付とは関係なくランダムとのこと。つまり、データをFirestoreに保存するときに、日付データも保存しないといけない。
https://hi1280.hatenablog.com/entry/2017/11/12/155257
2017-11-12
AngularFireでRealtime DatabaseからCloud Firestoreに変更した
https://blog.tplg.co.jp/2018/08/21/firebase-vuejs-chat-explanation/
グラミング
【解説編】Cloud Firestore(Firebase)とVue.jsを利用して1時間でチャットサービスを作ろう
2018年8月21日
Firestoreからの警告
https://qiita.com/teramotodaiki/items/b3592326579166003102
→結局よくわからかなった。
https://www.katonobo.com/entry/cloudfirestore-timestamp
上記サイトによると、以下でよいらしい!!!
db.collection('comments').add({ timestamp: Date.now() })
英語のリンク
https://github.com/vuetifyjs/vuetify/issues/238#issuecomment-341274460
Vuetify公式のimage uploaderは2018年12月現在、まだないらしい。
https://lovemewithoutall.github.io/it/vue-image-upload-to-firestorage/
Vue image uploader to Firebase Cloud Storage
https://medium.freecodecamp.org/how-to-build-a-flexible-image-uploader-component-using-vue-js-2-0-5ee7fc77516
How to build a flexible image uploader component using Vue.js 2.0
Go to the profile of Cathy Ha
Cathy Ha
Aug 12 2018
https://time2hack.com/2017/10/upload-files-to-firebase-storage-with-javascript/amp/
Upload Files to Firebase Storage with JavaScript
by Pankaj
2017-10-15
https://codeburst.io/vue-crud-x-a-highly-customisable-crud-component-using-vuejs-and-vuetify-2b1539ce2054
A highly customisable CRUD component using VueJS and Vuetify
Go to the profile of aaron gong
aaron gong
Jan 7
nuxt.jsとFirestore
https://techblog.scouter.co.jp/entry/2017/12/23/234209
20171223
Nuxt.jsとFirebase/Firestoreで動的コンテンツをPWAする
https://qiita.com/_takeshi_24/items/3ee051e1db1b3e8da106
@_takeshi_24
2018年10月28日に更新
Nuxt v2とFirebase(CloudFirestore)でPWA対応Webアプリ開発
Cloud FunctionsではNode.js v6.11.5しか利用できません。
https://qiita.com/iida_teco/items/80f37f4a461668543d2c
@iida_teco
2018年12月23日に更新
TECOTEC Advent Calendar 201822日目
Nuxt.jsをFirebaseでSSRするための開発環境をDockerで作る
(引用ここから)
まずは、Node.jsのv6.11.5とv8.11.1をインストールします。
なぜ2つもインストールするかというとNuxt.jsのv2では、Node.jsのv8以降が必要になりますが、ローカルでFirebase Functionsの動作確認をするために必要なモジュール@google-cloud/functions-emulatorがv6以前にしか対応していないためです。
そのため上記モジュールに依存しているcreate-nuxt-appはv6.11.5を使ってインストールすることになります。
(引用ここまで)
リンク
作成中