내일배움캠프 13주차 TIL

내일배움캠프 13주차 13-2 (firebase image upload)

YOOYOUNGJAE 2023. 1. 26. 20:58
728x90

먼저 만들고자하는 프로젝트 터미널에 npm install firebase 를 작성하여

라이브러리를 설치해준다

 

firebase.js

import { initializeApp } from "firebase/app"
import { getAnalytics } from "firebase/analytics"
import { getStorage } from "firebase/storage"

const firebaseConfig = {
    apiKey: "AIzaSyAioEYGuhjTExrUovMIy2DYb4IZKpGHIGk",
    authDomain: "numanna-4bc9a.firebaseapp.com",
    projectId: "numanna-4bc9a",
    storageBucket: "numanna-4bc9a.appspot.com",
    messagingSenderId: "588272405068",
    appId: "1:588272405068:web:5fd18b060694441a6582e9",
    measurementId: "G-3MQN7KE9R0"
}

const app = initializeApp(firebaseConfig)
const analytics = getAnalytics(app)
export const storage = getStorage(app)

imageupload.jsx

import React, { useState } from "react"
import { storage } from "./firebase"
import { ref, uploadBytes, getDownloadURL } from "firebase/storage"
import { Avatar } from "@mui/material"

export default function ImageUpload() {
    const [image, setImage] = useState(null)
    const [url, setUrl] = useState(null)

    const handleImageChange = (e) => {
        if (e.target.files[0]) {
            setImage(e.target.files[0])
        }
    }

    const handleSubmit = () => {
        const imageRef = ref(storage, "image")
        uploadBytes(imageRef, image)
            .then(() => {
                getDownloadURL(imageRef)
                    .then((url) => {
                        setUrl(url)
                    })
                    .catch((error) => {
                        console.log(error.message, "Error uploading")
                    })
                setImage(null)
            })
            .catch((error) => {
                console.log(error.message, "Error uploading")
            })
    }

    return (
        <div>
            <Avatar
                alt="Remy Sharp"
                src={url}
                sx={{ width: 150, height: 150 }}
            />
            <input type="file" onChange={handleImageChange} />
            <button onClick={handleSubmit}>이미지변경</button>
        </div>
    )
}

상단 파일명과 코드를 동일하게한후 변경하면 사진을 업로드할수있는 로직이생긴다

 

728x90