Firebase 업로드 파일 사용법

Firebase를 사용하여 웹에서 이미지를 업로드하고, 업로드한 이미지의 URL을 MongoDB에 저장하여 관리하는 방법입니다. 이를 통해 제품 등록 등의 기능을 구현할 수 있습니다.



Firebase upload-files



준비 단계

  1. Firebase 라이브러리 설치:

    yarn add firebase
    
  2. Firebase 프로젝트 생성: Firebase 홈페이지에서 로그인한 후 프로젝트를 생성합니다.

  3. 앱 설정 코드 복사: Firebase 프로젝트에서 앱을 만들고, 제공된 설정 코드를 복사합니다.

  4. Storage 설정: Firebase Console에서 Storage를 시작합니다. 이때 규칙은 모두 허용으로 설정해야 하며, 설정하지 않을 경우 403 접근 실패 에러가 발생할 수 있습니다.

  5. Firebase 초기화: VS Code에서 firebase.js 파일을 생성하고 복사한 설정 코드를 붙여넣습니다.

  6. 완성본 참고: 예제 소스는 아래 링크를 참고하세요:



코드 예제

firebase.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: // ... hide
  authDomain: 
  projectId: 
  storageBucket: 
  messagingSenderId: 
  appId: 
  measurementId: 
};

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

export default app;


NewProduct.jsx

// 파일 업로드
const handleClick = (e) => {
  e.preventDefault();
  const fileName = new Date().getTime() + file.name; // 고유한 파일명 생성
  const storage = getStorage(app);
  const storageRef = ref(storage, fileName);
  const uploadTask = uploadBytesResumable(storageRef, file);
  
  // Register three observers:
  // 1. 'state_changed' observer, called any time the state changes
  // 2. Error observer, called on failure
  // 3. Completion observer, called on successful completion
  uploadTask.on(
    "state_changed",
    (snapshot) => {
      // Observe state change events such as progress, pause, and resume
      // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
      const progress =
        (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log("Upload is " + progress + "% done");
      switch (snapshot.state) {
        case "paused":
          console.log("Upload is paused");
          break;
        case "running":
          console.log("Upload is running");
          break;
        default:
      }
    },
    (error) => {
      // Handle unsuccessful uploads
    },
    () => {
      // Handle successful uploads on complete
      // For instance, get the download URL: https://firebasestorage.googleapis.com/...
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        const product = { ...inputs, img: downloadURL, categories: cat };
        addProduct(product, dispatch); // DB에 저장
      });
    }
  );
};



주의 사항

  • Storage 규칙 설정: Firebase Storage 규칙이 제대로 설정되지 않으면 파일 업로드가 실패할 수 있습니다.
  • 에러 처리: 업로드 실패 시 적절한 에러 처리 로직을 추가하세요.

댓글남기기