FirebaseのStorageを利用する~画像データにて~

Expoでプロジェクトを作成すると、assetsフォルダにfavicon.pngという画像が用意されている。これを、FirebaseのStorageにアップロードしてみる。そして

アップロードしたファイルをダウンロードする。そして、アップロードしたファイルを削除する。

Firebase 10.1.0

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button, Image } from 'react-native';
import {deleteObject, getStorage, ref} from 'firebase/storage';
import {uploadBytesResumable, getDownloadURL} from 'firebase/storage';
import {initializeApp, getApps} from 'firebase/app';
import {initializeAuth,getReactNativePersistence} from 'firebase/auth';
import React from 'react';
import {Asset} from 'expo-asset';

const firebaseConfig = {
  apiKey: "AIz",
  authDomain: "sampl",
  projectId: "sam0",
  storageBucket: "samplet.com",
  messagingSenderId: "40",
  appId: "1:44224a07"
};

const storage = getStorage();

// アップロードするファイル
import favicon from './assets/favicon.png';
// FirebaseのStrorageに配置するパスを定義
const FAVICON_PATH = 'img/favicon.png';
 
class Contents extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imageUrl: null
    };
    this.downloadFile = this.downloadFile.bind(this);
  }


  uploadFile() {
    const { uri } = Asset.fromModule(favicon);
    fetch(uri)
    .then(res => res.blob())
    .then(blob => {
      const storageRef = ref(storage,FAVICON_PATH);
      uploadBytesResumable(storageRef, blob);
    });
  }

  downloadFile() {
    const storageRef = ref(storage,FAVICON_PATH);
    // Storageに置かれたファイルに対してダウンロードに利用できるURLを要求
    getDownloadURL(storageRef)
    .then(url => {
      // 取得したURLをstateに設定
      this.setState({imageUrl: url})
    })
  }

  deleteFile() {
    const storageRef = ref(storage,FAVICON_PATH);
    // Storageに置かれたファイルに対して削除を要求
    deleteObject(storageRef);
  }
 
  render() {
    return (
      <View>
        <View>
          <Button title="アップロード" onPress={this.uploadFile} />
        </View>
        <View style={{marginTop: 20, alignItems: 'center'}}>
          <Button title="ダウンロード" onPress={this.downloadFile} />
          {
            this.state.imageUrl &&
            <Image
              source={{uri: this.state.imageUrl}}
              style={{width: 48, height: 48, marginTop: 10}}
            />
          }
        </View>
        <View style={{marginTop: 20}}>
          <Button title="削除" onPress={this.deleteFile} />
        </View>
      </View>
    );
  }
}
 
export default function App() {
  return (
    <View style={styles.container}>
      <Contents />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

 

firebaseConfigを自分のものにすると完成である。

 

次に上のものを、機能型コンポーネントで作成してみる。

(作成中)