팀 프로젝트로 진행 중인
사이트에
마이페이지 프로필 사진을
수정할 수 있게 구현했다
Storage 에서 제공하는
api를 이용하여 이미지 업로드
// Firebase 모듈 가져오기
import { storage } from '../../firebase';
import { getDownloadURL, ref, uploadBytes } from 'firebase/storage';
// React 및 스타일드 컴포넌트 가져오기:
import React, { useState } from 'react';
import styled from 'styled-components';
// ImgUpload 컴포넌트 정의
const ImgUpload = () => {
const [selectedImg, setSelectedImg] = useState(
'https://firebasestorage.googleapis.com/v0/b/fir-e-9aec4.appspot.com/o/folder%2F_7fdc97b7-c89c-41b1-bd84-7cfb1b07a7d2.jpg?alt=media&token=e0c9e857-d8c8-49c2-931a-2b6fa45d8db0'
);
// 파일 선택 시 실행될 함수
const handleFileSelect = async (event) => {
const imageFile = event.target.files[0];
await handleUpload(imageFile);
};
// 파일 업로드 함수
const handleUpload = async (imageFile) => {
if (imageFile) {
// 이미지를 저장할 경로 설정
const imageRef = ref(storage, `folder/${imageFile.name}`);
// 이미지 업로드
await uploadBytes(imageRef, imageFile);
// 업로드한 이미지의 다운로드 URL 가져오기
const downloadURL = await getDownloadURL(imageRef);
// 상태 업데이트
setSelectedImg(downloadURL);
}
};
return (
<>
{/* 파일 업로드를 위한 라벨 및 이미지 표시 */}
<Upload>
<input type="file" onChange={handleFileSelect} />
<ProfileImg src={selectedImg} alt="Selected Image" />
</Upload>
</>
);
};
// 스타일링
const Upload = styled.label`
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
border-radius: 50%;
overflow: hidden;
text-align: center;
cursor: pointer;
input {
display: none;
}
`;
const ProfileImg = styled.img`
width: 100%;
height: 100%;
object-fit: cover;
`;
export default ImgUpload;
변경된 이미지의
다운로드 주소를 가져와서
useState를 통해
상태 업데이트할 수 있게 하였다
'✍️ 스파르타 TIL' 카테고리의 다른 글
[TIL] sparta 39일차 - Axios, JSON Server (0) | 2023.11.28 |
---|---|
[TIL] sparta 36일차 - 실수로 API 키를 올렸을 때 바로 직전 커밋 삭제로 해결하는 방법 (0) | 2023.11.23 |
[TIL] sparta 34일차 - Live Share (0) | 2023.11.21 |
[TIL] sparta 30일차 (0) | 2023.11.15 |
[TIL] sparta 29일차 - JSON (0) | 2023.11.14 |