react로 twitter 만들기(3)

dooga·2024년 4월 26일
0

프로젝트

목록 보기
5/5

Firebase Storage

  • 클라우드 스토리지를 활용해 사용자가 업로드한 미디어 파일(이미지, 비디오, 음악 등)을 보관하고 관리할 수 있는 서비스
  • 장점
    • 확장성이 좋음 : Google Cloud Storage 인프라 기반으로 작동. 필요한만큼 자동으로 확장되어 어떤 규모의 앱이든 쉽게 대응 가능&빠른 액세스 제공
    • 인증 및 보안 : Firebase Authentication과 연동하여 파일에 대한 접근 권한 설정 가능
    • 다양한 파일 형식 지원 : 이미지, 비디오, 음악, 문서 등 다양한 형식 지원
    • 편리한 이미지 조작 : Firebase Storage로 업로드된 이미지를 리사이징 하거나, 필터를 적용하는 등의 작업을 쉽게 수행 가능

storage 시작하기

export const storage = getStorage(app);

파일 업로드

  • Cloud Storage에 파일을 업로드하려면 우선 파일 이름을 포함하여 파일의 전체 경로를 가리키는 참조를 만든다.
  • uploadString 메서드
  • 공식문서
const key = `${user?.uid}/${uuidv4()}`; // img이름 중복되지 않기 위해
const storageRef = ref(storage, key);

// 업로드하기
 const data = await uploadString(storageRef, imageFile, "data_url");
// 파일의 다운로드 URL 가져오기
 imageUrl = await getDownloadURL(data.ref);

프로필 이미지 수정·삭제

const onSubmit = async (e: any) => {
    e.preventDefault();

    let key = `${user?.uid}/${uuidv4()}`;
    const storageRef = ref(storage, key);
    let newImageUrl = null;

    try {
      // 기존 유저이미지가 firebase storage 이미지일 경우에만 삭제
      if (user?.photoURL && user?.photoURL.includes(STORAGE_DOWNLOAD_URL_STR)) {
        const imageRef = ref(storage, user?.photoURL);
        if (imageRef) {
          await deleteObject(imageRef).catch((error) => console.log(error));
        }
      }

      // 이미지 업로드
      if (imageUrl) {
        const data = await uploadString(storageRef, imageUrl, "data_url");
        newImageUrl = await getDownloadURL(data?.ref);
      }

      // updateProfile 호출
      if (user) {
        await updateProfile(user, {
          displayName: displayName || "",
          photoURL: newImageUrl || "",
        })
          .then(() => {
            toast.success("프로필이 업데이트 되었습니다.");
            navigate("/profile");
          })
          .catch((error) => {
            console.log(error);
          });
      }
    } catch (error) {
      console.log(error);
    }
  };

0개의 댓글