前提
- ionic環境準備とプロジェクトを作成
- https://qiita.com/alingogo/items/fc5eece405cdc6ffc025
- Firebase configとアプリ設定、モジュールのインストール、config内容を導入を以下の文書を参照してください
- https://qiita.com/alingogo/items/a049a73f1ec20a243573
native plugin導入
$ ionic cordova plugin add https://github.com/apache/cordova-plugin-camera.git
firebase storageのルールを変更
- 開発 -> storage -> ルール
service firebase.storage {
match /b/<appname>.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
実装
- アップロードページを作成
$ ionic g page image_upload
- html
image_upload.html
<ion-content padding>
<div style="justify-content:center">
<button ion-button (click)="capture()">写真を撮る</button>
</div>
<img [src]="captureDataUrl" *ngIf="captureDataUrl"/>
<button ion-button (click)="upload()" *ngIf="captureDataUrl">アップロード</button>
</ion-content>
- ロジック
image_upload.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import firebase from 'firebase';
@IonicPage()
@Component({
selector: 'page-image-upload',
templateUrl: 'image-upload.html',
})
export class ImageUploadPage {
captureDataUrl: string;
constructor(private camera: Camera) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ImageUploadPage');
}
capture() {
const cameraOptions: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
};
this.camera.getPicture(cameraOptions).then((iData) => {
this.captureDataUrl = 'data:image/jpeg;base64,' + iData;
}, (err) => {
console.log('error');
});
}
upload() {
let sRef = firebase.storage().ref();
const filename = Math.floor(Date.now() / 1000);
const imageRef = sRef.child(`images/${filename}.jpg`);
imageRef.putString(this.captureDataUrl, firebase.storage.StringFormat.DATA_URL).then((snapshot)=> {
console.log('upload succes');
});
}
}