• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 JavaScript, TS 게시판 파이어베이스 이미지 업로드 비어있을때

파이어베이스 이미지 업로드 비어있을때

4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 글쓴이
  • #20969

    MidNight
    참가자

    파이어베이스 이미지 올리는 것 까지 구현했는데 이미지를 안올리고 글만 작성했을시  undifined 라고 나옵니다. 

    Uncaught TypeError: Cannot read properties of undefined (reading 'name')  이런 에러로그가 나오는데

    이미지 값을 안넣어서 그런것 같은데 안 넣어도 작동되게 할수있는 방법이 있을까요

    #20970

    MidNight
    참가자

       $("#send").click(function(){
         
              var file = document.querySelector("#image").files[0];
              var storageRef = storage.ref();
              var 저장할경로 = storageRef.child('image/' + file.name);
              var 업로드작업 = 저장할경로.put(file)

              업로드작업.on( 'state_changed',
        // 변화시 동작하는 함수
        null,
        //에러시 동작하는 함수
        (error) => {
          console.error('실패사유는', error);
        },
        // 성공시 동작하는 함수
        () => {      
          업로드작업.snapshot.ref.getDownloadURL().then((url) => {
            console.log('업로드된 경로는', url);
            const today = new Date();
            const newtoday = today.toLocaleString()
            var 저장할거 = {
              제목: $("#title").val(),
              가격: $("#price").val(),
              내용: $("#content").val(),
              날짜: newtoday,
              이미지: url,
                 // uid: JSON.parse(localStorage.getItem("user")).uid,
              // 이름: JSON.parse(localStorage.getItem("user")).displayName,
            }

            db.collection("product").add(저장할거).then((result) => {
              // window.location.href = '/index.html'
              console.log(result);
            }).catch((err) => {
              console.log(err)
            })
          });

     

    여기서 if 구문을 써야할 꺼 같은데 image가 비어있을때와  있을때 두가지로넣어줘야할것같은데 잘모르겠습니다.

    #20971

    MidNight
    참가자

    if 구문으로  해결했습니다. 코드는 

       $("#send").click(function(){
         
              var file = document.querySelector("#image").files[0];
              if(file != null){
                var storageRef = storage.ref();
              var 저장할경로 = storageRef.child('image/' + file.name);
              var 업로드작업 = 저장할경로.put(file)

              업로드작업.on('state_changed',
                // 변화시 동작하는 함수
                null,
                //에러시 동작하는 함수
                (error) => {
                  console.error('실패사유는', error);
                },
                // 성공시 동작하는 함수
                () => {
                  업로드작업.snapshot.ref.getDownloadURL().then((url) => {
                    console.log('업로드된 경로는', url);
                    const today = new Date();
                    const newtoday = today.toLocaleString()
                    var 저장할거 = {
                      제목: $("#title").val(),
                      가격: $("#price").val(),
                      내용: $("#content").val(),
                      날짜: newtoday,
                      이미지: url,
                      // uid: JSON.parse(localStorage.getItem("user")).uid,
                      // 이름: JSON.parse(localStorage.getItem("user")).displayName,
                    }

                    db.collection("product").add(저장할거).then((result) => {
                      // window.location.href = '/index.html'
                      console.log(result);
                    }).catch((err) => {
                      console.log(err)
                    })
                  });
                }
              );
              }else{
                const today = new Date();
                const newtoday = today.toLocaleString()
                var 저장할거 = {
                  제목: $("#title").val(),
                  가격: $("#price").val(),
                  내용: $("#content").val(),
                  날짜: newtoday

                  // uid: JSON.parse(localStorage.getItem("user")).uid,
                  // 이름: JSON.parse(localStorage.getItem("user")).displayName,
                }

                db.collection("product").add(저장할거).then((result) => {
                  // window.location.href = '/index.html'
                  console.log(result);
                }).catch((err) => {
                  console.log(err)
                })
             
              }
           

            });

     

    이렇게 썼는데   작동은 됩니다. 그런데  이렇게 하는게 효율적인 코드일까요? 다른방법도 존재한다면 궁금합니다.

    #20983

    codingapple
    키 마스터

    경우에 따라서 분기를 주고 싶으면 if문밖에 없습니다

    중복되는것 같은 코드들은 나중에 함수로 묶을 수도 있습니다 

4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠