JadeCode

[혼프] 혼자하는 프로젝트 3. firebase storage 본문

개발

[혼프] 혼자하는 프로젝트 3. firebase storage

z-zero 2023. 3. 31. 22:00

Firebase Storage 사진저장 방법

 

사진을 저장하기 위해 또 clientApp.ts에서 새롭게 import할 라이브러리가 있다.

// firebase/clientApp.ts
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
import "firebase/compat/auth";
import firebaseConfig from "firebaseConfig.json";

const app = firebase.initializeApp(firebaseConfig);

const firestore = getFirestore(app); //DB
const firestorage = getStorage(app); //사진저장
const fireAuth = firebase.auth(); //인증

export { firestore, fireAuth, firestorage };

getStorage를 불러온 후 export 해 준다.

 

//imageUpload.ts
//이미지 업로드 함수
//return 값 Promise<string>
import { firestorage } from "firebase/clientApp";

import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { v4 as uuidv4 } from "uuid"; //firebase image upload용 id

const firebaseImageUpload = (files: FileList): Promise<string> => {
  return new Promise(async (resolve, reject) => {
    try {
      const storageRef = ref(firestorage, uuidv4());
      const uploadTask = uploadBytesResumable(storageRef, files[0]);

      uploadTask.on(
        "state_changed",
        (snapshot) => {
          const progress =
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          progress === 100 && alert("Upload is " + progress + "% done");
          switch (snapshot.state) {
            case "paused":
              console.log("Upload is paused");
              break;
            case "running":
              console.log("Upload is running");
              break;
          }
        },
        (error) => {
          // Handle unsuccessful uploads
          reject(error);
        },
        async () => {
          // Handle successful completion of the upload task here
          const downloadUrl = await getDownloadURL(uploadTask.snapshot.ref);
          console.log(
            `File uploaded successfully, download URL: ${downloadUrl}`
          );
          resolve(downloadUrl);
        }
      );
    } catch (error) {
      reject(error);
    }
  });
};
export default firebaseImageUpload;

 

사용법

위에서 정리한 imageUpload import하기
  ....
  const handleFileUpload = async (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      await imageUpload(e.target.files).then((res) => {
        setForm([...res]);
        }
      });
    }
  };
  
  ...
  
  return (
  ...
<input
  id="imageInput"
  type="file"
  accept="image/*"
  onChange={handleFileUpload}
  multiple
/>
);

 

참고

https://firebase.google.com/docs/storage/web/upload-files?hl=ko 

 

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

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

firebase.google.com

 

Comments