파이어베이스에 글과 이미지 업로드 하기 - Firebase Storage

파이어베이스에 글과 이미지 업로드 하기 - Firebase Storage

const db = firebase . firestore ();

const storage = firebase . storage ();

// 버튼이 클릭이 되면 function이 실행이 되도록 합니다.

document . querySelector ( '.image__button' ). addEventListener ( 'click' , function () {

// 파일 업로드 관련

const imgFile = document . querySelector ( '.image__input' ). files [ 0 ];

const storageRef = storage . ref ();

const imgLocation = storageRef . child ( 'image/' + imgFile . name );

const uploadStart = imgLocation . put ( imgFile );

uploadStart . on (

'state_changed' ,

null ,

( error ) => {

console . error ( '실패사유는 :' , error );

},

// 성공시 동작하는 함수

function

() {

uploadStart . snapshot . ref . getDownloadURL (). then (( url ) => {

//snapshot.ref.getDownloadURL() 은 통상적으로 주어지는 기능

//url을 가져오기 위해서 사용된다.

const toSave = {

date : new Date (),

image : url , //업로드에 성공한 이미지 url을 담아줍니다.

};

db . collection ( 'blog' )

. add ( toSave )

. then (() => {

window . location . href = '/index.html' ;

})

. catch (( err ) => {

console . log ( err );

});

});

}

);

from http://gnews365.tistory.com/23 by ccl(A) rewrite - 2021-11-05 19:27:41