1
1

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 5 years have passed since last update.

ionicでfirebaseへ画像アップロードできるように

Posted at

前提

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');
    });
  }
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?