inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

따라하며 배우는 리액트, 파이어베이스 - 채팅 어플리케이션 만들기[2023.12 리뉴얼]

프로필 이미지 수정(2) Firebase 스토리지에 이미지 업로드

ref is not a function 해결

1040

황경훈
0

파이어 베이스 업데이트가 원인인지는 잘 모르겠으나.
강의 내용대로 하면 몇 가지 오류 사항이 있을 겁니다.
 
일단 mime-types 도 에러가 나서 저는 따로 file.type을 받아와서 처리했습니다.
 
 const handleUploadImage = async (event) =>{
const file = event.target.files[0];
    const metadata = { contentType: file.type};
 //스토리지에 파일 저장하기
 console.log('file',file);
 console.log('meta',metadata);
 
일단 제가 해결 했던 방법은.
아래와 같이 firebase/storeage를 import 해줍니다.
 
import { getStorage, ref, uploadBytes } from "firebase/storage";
 
그 이후에 getStorages() 와, storageRef 부분을 선언해줍니다.
 
const storage = getStorage();
 const storageRef = ref(storage,  `user_image/${user.uid}`);
 
 try{

// 'file' comes from the Blob or File API
const uploadTask = uploadBytes(storageRef, file, metadata);
 
이후엔 uploadBytes를 이용해서 인자값으로 저렇게 넣어주면 일단 데이터는 들어갈텐데 만약 403 에러가 나온다면
 
storage - Rules 에서
allow read,write: if request.auth != null; 로 바꿔주면 해결 될겁니다.


참고 문헌 :
https://firebase.google.com/docs/storage/web/upload-files
 
https://stackoverflow.com/questions/38671444/user-does-not-have-permission-to-access-this-object-firebase-storage-android
 
전체 소스 코드
import React,{useRef} from 'react';
import {GiBroadsword} from 'react-icons/gi';
import Dropdown from 'react-bootstrap/Dropdown';
import Image from 'react-bootstrap/Image';
import { useDispatch, useSelector } from 'react-redux';
import firebase from '../../../firebase';
import { getStorage, ref, uploadBytes } from "firebase/storage";
// import mime from 'mime-types';

function UserPanel() {
  const user = useSelector(state => state.user.currentUser)
  const inputOpenImageRef = useRef();


  console.log(user)
  const handleLogout = () =>{
    firebase.auth().signOut();
  }
  const handleOpenImageRef = () =>{
    inputOpenImageRef.current.click();
  }

  const handleUploadImage = async (event) =>{
const file = event.target.files[0];
    const metadata = { contentType: file.type};
 //스토리지에 파일 저장하기
 console.log('file',file);
 console.log('meta',metadata);
 const storage = getStorage();
 const storageRef = ref(storage,  `user_image/${user.uid}`);
 
 try{

// 'file' comes from the Blob or File API
const uploadTask = uploadBytes(storageRef, file, metadata);
//   let uploadTask = uploadBytesResumable(strRef(storage, `user_image/${user.uid}`), file, metadata)
   
// console.log('upload',uploadTask);
 }catch(error){
console.log(error);
 }
  }

  return (
    <div>
      {/* Logo */}
      <h3 style = {{color:"white"}}>
          <GiBroadsword/> {""} ChatApp
      </h3>
      <div style ={{display:"flex", marginBottom: '1rem'}}>
          <Image src={user && user.photoURL}
          style={{width:'30p', height:'30px',marginTop:'3px'}}
          roundedCircle/>

          <input
            type="file"
            accept="image/jpeg, image/png"
            ref={inputOpenImageRef}
            style={{display:"none"}}
            onChange = {handleUploadImage}
          />
          <Dropdown>
              <Dropdown.Toggle
              style={{background:'transparent', boder:'0px'}}
              id="dropdown-basic">
                {user && user.displayName}
              </Dropdown.Toggle>

              <Dropdown.Menu>
                <Dropdown.Item onClick={handleOpenImageRef}>
                  프로필 사진 변경
                </Dropdown.Item>
                <Dropdown.Item onClick={handleLogout}>
                  로그아웃
                </Dropdown.Item>
              </Dropdown.Menu>
          </Dropdown>
      </div>
    </div>
  )
}

export default UserPanel;
 
 
 
 

답변 1

0

Frederick Gragg

Education is the most important and powerful tool in this world. It's not about studying and only getting good marks. h19-101-eun hcsa-ip network v4.0 provides authentic IT Certification exams preparation material guaranteed to make you pass in the first attempt.