본문 바로가기

ETC

Firebase 이미지 저장하기(storage)

반응형

<upload.html>

<!DOCTYPE html>
<html>
<head>
	<!-- jQuery  -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<link rel="stylesheet" href="style.css" />
</head>
<body>
업로드

<div class="container mt-3">
  <input type="text" class="form-control mt-2" id="title" placeholder="title">
  <textarea class="form-control mt-2" id="content">content</textarea>
  <input type="text" class="form-control mt-2" id="price" placeholder="price">
  <input class="form-control mt-2" type="file" id="image">
  <button class="btn btn-danger mt-3" id="send">올리기</button>

</div>


<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-storage.js"></script>

<script>
  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  var firebaseConfig = {
    apiKey: "AIzaSyCnowLA3wkZzoSX9kFHdq615-ZhUvdNj60",
    authDomain: "wjdb-647dc.firebaseapp.com",
    databaseURL: "https://wjdb-647dc-default-rtdb.firebaseio.com",
    projectId: "wjdb-647dc",
    storageBucket: "wjdb-647dc.appspot.com",
    messagingSenderId: "241186966612",
    appId: "1:241186966612:web:9843c62bd2c76613ae71c1",
    measurementId: "G-8HX4QXCKBQ"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>

<!-- <script src="app.js"></script> -->
<script>
  const db = firebase.firestore();
  const storage = firebase.storage();

  // 쓰기
  // db.collection('product').doc('상품3').set({ 제목: '변기'})
  // db.collection('product').add({제목: '변기'})

  $('#send').click(function() {

    var file = document.querySelector('#image').files[0];
    var storageRef = storage.ref();
    var file_path = storageRef.child('image/' + file.name);
    var 업로드작업 = file_path.put(file);

    업로드작업.on(
      'state_changed',
      null,
      (error)=>{
        console.err('실패사유는',error);
      },
      () => {
        업로드작업.snapshot.ref.getDownloadURL().then((url) => {
          console.log('업로드된 경로는', url);

          var upload = {
            제목: $('#title').val(),
            내용: $('#content').val(),
            가격: parseInt($('#price').val()),
            날짜: new Date(),  
            이미지: url
          }
          db.collection('product').add(upload).then((res) =>{
            console.log(res);
            // window.location.href="/index.html";
          }).catch((err) => {
            console.log(err);
          })
        })
      }
    )    
  })  
  
</script>
</body>
</html>
반응형