Daily Front_Minhhk

[firebase] storage 설정 (+ 파일 업로드, 다운로드) 본문

Project/ChatProject

[firebase] storage 설정 (+ 파일 업로드, 다운로드)

Minhhk 2023. 5. 10. 00:57

빌드에서 Storage 를 눌러 생성!

 

 

스토리지 위치는 당연 서울!

 

 

공식문서를 살펴보자 (Storage)

 

firebase.js 파일에서

 

const storage = getStorage(app) 
import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
  storageBucket: ''
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Cloud Storage and get a reference to the service
const storage = getStorage(app);

 

Blob 또는 File에서 업로드

적절한 참조를 만들었으면 uploadBytes() 메서드를 호출합니다. uploadBytes()는 자바스크립트 File  Blob API를 통해 파일을 가져와서 Cloud Storage에 업로드합니다.

import { getStorage, ref, uploadBytes } from "firebase/storage";

const storage = getStorage();
const storageRef = ref(storage, 'some-child');

// 'file' comes from the Blob or File API
uploadBytes(storageRef, file).then((snapshot) => {
  console.log('Uploaded a blob or file!');
});

 

공식문서를 참고하여

작성 ->>

 

1. uploadBytes(storageRef, file) 에서

storageRef
ref를 import 하여 인자로 storage 와 로그인한 유저의 개인 uid를 넣어 구별해준다.

 

 

2. 다음 file 부분은 <input type="file">로 등록한 이미지 파일을 가져오자

const file = e.target.files[0]

 

3. 파일 업로드 코드이다. snapshot 을 콘솔로 찍으면 

  //! 프로필사진 storage 업로드
  const uploadImg = async (e) => {
    // 업로드한 이미지 파일
    const file = e.target.files[0];
    console.log(file);

    const storageRef = ref(storage, userUid);

    try {
      //! 스토리지 파일 저장
      await uploadBytes(storageRef, file).then(
        (snapshot) => {
          console.log("Uploaded a blob or file!");
          console.log(snapshot)
        }
      );

    } catch (err) {
      console.log(err);
    }


  };

 

콘솔에서 찍은 결과를 볼 수가 있다.

파이어베이스 storage 에서도 확인

 

 

by

 

 

파이어베이스 스토리지에 이미지를 업로드하고 다운받고를 해보자

파이어베이스 스토리지에 이미지 업로드, 다운로드 하기

velog.io

 

 

웹에서 Cloud Storage로 파일 업로드  |  Firebase용 Cloud Storage

5월 10일, Google I/O에서 Firebase가 돌아옵니다. 지금 등록하기 의견 보내기 웹에서 Cloud Storage로 파일 업로드 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. Fireb

firebase.google.com

 

 


URL을 통해 데이터 다운로드

 

 

공식문서의 코드에서 요점은 아래와 같다.

getDownloadURL(ref(storage, 파일))
import { getStorage, ref, getDownloadURL } from "firebase/storage";

const storage = getStorage();
getDownloadURL(ref(storage, 'images/stars.jpg'))
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    const xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      const blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    const img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

 

>>

 

현재 프로젝트에서는 업로드한  사진을 가져올 것이기 때문에 변수를 생성하여 담아 주었다.

      let downStoragePhotoUrl = await getDownloadURL(ref(storage, userUid));

      console.log(downStoragePhotoUrl);

 

콘솔에 찍어보면 링크로 나온다!!

이것을 갖고 유저정보 업데이트를 해준다. {photoURL : downStoragePhotoUrl }

 

      // 파이어베이스 유저정보 업데이트
      await updateProfile(appAuth.currentUser, {
        photoURL: downStoragePhotoUrl,
      });

 

결과 화면 >>

 

 

by

 

웹에서 Cloud Storage로 파일 다운로드  |  Firebase용 Cloud Storage

5월 10일, Google I/O에서 Firebase가 돌아옵니다. 지금 등록하기 의견 보내기 웹에서 Cloud Storage로 파일 다운로드 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. Fi

firebase.google.com