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();
// アップロードするファイル
// FirebaseのStrorageに配置するパスを定義
class Contents extends React.Component {
constructor(props) {
super(props);
this.state = {
imageUrl: null
};
this.downloadFile = this.downloadFile.bind(this);
}
uploadFile() {
.then(res => res.blob())
.then(blob => {
uploadBytesResumable(storageRef, blob);
});
}
downloadFile() {
// Storageに置かれたファイルに対してダウンロードに利用できるURLを要求
getDownloadURL(storageRef)
.then(url => {
// 取得したURLをstateに設定
this.setState({imageUrl: url})
})
}
deleteFile() {
// 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
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: {
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
firebaseConfigを自分のものにすると完成である。
次に上のものを、機能型コンポーネントで作成してみる。
(作成中)