Firebase version 9
version8 과 version9 은 다른 문법을 써야 했음
이미지 와 DB 업로드 하려면
일단 기능들 땡겨오고..
import { storageService } from "./firebase.js";
import { dbService } from "./firebase.js";
import { authService } from "./firebase.js";
//파이어베이스 js 를 따로 만들어 놨음
import {
ref,
uploadString,
getDownloadURL,
deleteObject,
uploadBytes,
uploadBytesResumable
} from "https://www.gstatic.com/firebasejs/9.14.0/firebase-storage.js";
//파이어베이스 js에 없는 것들은 cdn에서 따로 떙겨옴
import {
doc,
addDoc,
updateDoc,
deleteDoc,
collection,
orderBy,
query,
getDocs,
} from "https://www.gstatic.com/firebasejs/9.14.0/firebase-firestore.js";
//파이어베이스 js에 없는 것들은 cdn에서 따로 떙겨옴
코드 작성
// uploading 이란 버튼을 누르면 아래와 같은 함수가 작동됨
export const uploading = async (event) => {
const imgFile = document.querySelector('#image').files[0]
//이미지 파일을 해당 id 에서 떙겨 온다
const storageRef = ref(storageService, 'post' + imgFile.name)
//이미지를 스토리지에 저장시 저장할 위치를 지정한다.
const uploadfile = uploadBytes(storageRef, imgFile)
//uploadByte 함수를 사용 하여 이미지를 업로드 한다.
const uploadTask = uploadBytesResumable(storageRef, imgFile)
//이미지 원본은 DB에 저장 되는게 아니니 DB에는 이미지 파일에 대한 URL 저장해야한다.
// uploadTask가 실행된다면
uploadTask.on('state_change',
// 변화시 동작하는 함수
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done')
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
//에러시 동작하는 함수
(error) => {
console.error("실패사유는:", error);
},
//성공시 동작하는 함수
() => {
getDownloadURL(uploadTask.snapshot.ref).then((photoURL) => {
console.log('업로드된 경로는:', photoURL);
const category = document.getElementById("category")
const title = document.getElementById("title")
const content = document.getElementById("content");
const score = document.getElementById("score")
const { uid, displayName } = authService.currnetUser
const today = new Date();
const year = today.getFullYear();
const month = ('0' + (today.getMonth() + 1)).slice(-2);
const day = ('0' + today.getDate()).slice(-2);
const dateString = year + month + day;
try {
addDoc(collection(dbService, "post"), {
카테고리: category.value,
제목: title.value,
내용: content.value,
평점: parseInt(score.value),
작성일: parseInt(dateString),
작성자: uid,
이미지: photoURL,
닉네임: displayName
});
alert("등록완료");
} catch (error) {
alert(error);
console.log("error in addDoc:", error);
}
})
})
}
'개발 일지 > 개발 일지' 카테고리의 다른 글
내일배움캠프 Week 4 (0) | 2022.11.28 |
---|---|
내일배움캠프 Day 20 (0) | 2022.11.28 |
내일배움캠프 Day 18 (0) | 2022.11.24 |
내일배움캠프 Day 17 (0) | 2022.11.23 |
내일배움캠프 Day 16 (0) | 2022.11.22 |