본문 바로가기
Frontend/React-Native

[React-Native] Firebase에 이미지 업로드

by 모너아링 2023. 6. 1.

Instroduction

Firebase의 storage에 이미지를 업로드하는 방법을 알아보려고 한다.

 

// result
{"assets": [{"fileName": "rn_image_picker_lib_temp_a56ab75e-5409-4700-8f51-6a4611a148ae.jpg", "fileSize": 199797, "height": 1280, "type": "image/jpeg", "uri": "file:///data/user/0/com.android_rn/cache/rn_image_picker_lib_temp_a56ab75e-5409-4700-8f51-6a4611a148ae.jpg", "width": 960}]}

 

이미지를 선택하고 나서 result로 출력되는 객체는 다음과 같다.

여기서 fileName, localUri를 이용한다.

 

1. 로컬 URI에서 이미지 가져오기

const response = await fetch(localUri);

 

2. 이미지 데이터를 Blob 객체로 변환

const blob = await response.blob();

 

3. Firebase Storage에 접근

const storageRef = storage.refFromURL("firebase storage 주소");

 

4. 업로드할 파일 참조

const fileRef = storageRef.child(fileName);

 

5. Storage에 업로드

await fileRef.put(blob);

 

전체 코드

const response = await fetch(localUri);
const blob = await response.blob();

const storageRef = storage.refFromURL("gs://g-3280-project.appspot.com");
const fileRef = storageRef.child(fileName);

await fileRef.put(blob);

 

 

오류 발생

코드를 실행했을 때 접근 권한 오류가 발생했다.

 

해결책

1. firebase storage로 이동

2. Rule 탭 선택

3. 보안 규칙 수정 (쓰기 권한 부여)

//수정 전
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
  }
}

//수정 후
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

 

잘 업로드 된 것을 확인할 수 있다.