[React Native] Firebase Storage 파일 업로드

bi_sz·2023년 11월 23일
0

ReactNative

목록 보기
36/37
post-thumbnail

💫 라이브러리 설치

> npx expo install @react-native-firebase/storage
> npx expo install expo-image-picker

💫 imagePicker

[
        "expo-image-picker",
        {
          "photosPermission": "The app accesses tour photos to let you share them with your friends."
        }
      ]

app.json 에 해당 코드를 추가해주었습니다.

App.js 에서 기존 코드를 날리고 ImagePicker 관련 코드를 추가해주었습니다.

> npx expo prebuild
> npm run android

app.json 파일을 수정했기 때문에, prebuild 를 진행한 후 실행해줍니다.

사진을 선택하고 편집도 가능합니다. Choose를 하고나면 Asset에 내용이 들어가고, 캔슬하면 false 로 들어갑니다.

asset 에 정보가 담긴 모습입니다.

💫 클라우드 스토어에 업로드

https://rnfirebase.io/storage/usage
공식 홈페이지에서 사용법이 설명되어있습니다.

App.jsstorage 에 이미지 uri 와, fileName 을 보내줍니다.

이미지를 선택해주면 firebase 에 저장되는 로그가 표시됩니다.

firebase 에서 저장된 이미지를 확인할 수 있습니다.

💫 저장된 이미지 다운로드

마지막에 올린 업로드를 담을 lastUploadImage 와 선택한 이미지를 담을 selectedImage useState 를 추가해주었습니다.

selectImage 가 있을 경우에만 보여주도록 추가해주고 다운로드 버튼도 추가해주었습니다.

이미지를 올리면 마지막으로 올린 이미지가 선택되어 보여지고, 다운로드 버튼을 누르면 해당 url 가 콘솔에 뜨는 모습입니다.

이제 해당 urlexpo fileSystem 을 사용하여 다운로드 해주겠습니다.

💫 expo fileSystem

> npx expo install expo-file-system
> npx expo prebuild
> npm run android

expo-file-system 라이브러리를 설치하고, 빌드해준 후 다시 실행해주었습니다.

App.js 에서 파일 시스템을 이용하여 저장해주었습니다.

파일로 잘 저장된 모습입니다.


App.js 전체 코드

import { useCallback, useState } from 'react';
import { Button, StyleSheet, View, Platform, Image } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import storage from '@react-native-firebase/storage';
import * as FileSystem from 'expo-file-system';

export default function App() {
  const [selectedImage, setSelectedImage] = useState(null);
  const [lastUploadImage, setLastUploadImage] = useState(null);

  const onPressPickFile = useCallback(async()=>{
    const pickResult = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing:true,
      quality:1,
    })

    if(pickResult.canceled){
      return;
    }

    const image = pickResult.assets[0];
    setSelectedImage(image);
    const uri = image.uri;
    const fileNameArray = uri.split('/');
    const fileName = fileNameArray[fileNameArray.length-1];

    console.log(fileName);

    const putResult = await storage().ref(fileName).putFile(Platform.OS === 'ios' ? uri.replace('file://', '') : uri);
    console.log(putResult);
    setLastUploadImage(putResult);
  }, [])

  const onPressDownloadImage = useCallback(async()=>{
    const downloadUrl = await storage().ref(lastUploadImage.metadata.fullPath).getDownloadURL();

    const { uri } = await FileSystem.createDownloadResumable(
      downloadUrl,
      FileSystem.documentDirectory + lastUploadImage.metadata.name,
      {}
    ).downloadAsync();

    console.log(uri,'uri');

  }, [lastUploadImage])

  return (
    <View style={{flex:1, alignItems:'center', justifyContent:'center'}}>
      {selectedImage !== null && (
        <Image source={{uri:selectedImage.uri}} style={{width:200, height:200,}}/>
      )}
      <Button title='PICK FILE' onPress={onPressPickFile}></Button>

      <Button title='DOWNLOAD FILE' onPress={onPressDownloadImage}></Button>
    </View>
  )
}

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

0개의 댓글