image 업로드 (data_url)

HYOJIN·2021년 10월 4일
0

React

목록 보기
8/9
post-thumbnail

post.js

import

import {firestore, storage} from '../../shared/firebase'
import { actionCreators as imageActions } from './image';

image 미리보기 가져오기

const _image = getState().image.preview;
console.log(typeof _image)  // string

image 업로드

  • 문자열로 업로드 - firebase docs 참고

  • 중복파일명이 생기지 않도록 user_id, 날짜 설정

// 문자열로 업로드
const _upload = storage.ref(`images/${user_info.user_id}_${new Date().getTime()}`).putString(_image,'data_url');

// 업로드 확인
_upload.then(snapshot =>{
    snapshot.ref.getDownloadURL().then(url => {
        console.log(url)

        return url;
    }).then(url =>{  // 체이닝
        // image url 사용가능
        postDB.add({...user_info, ..._post, image_url: url})
        
        .then((doc) =>{
            let post = {user_info, ..._post, id:doc.id,image_url: url};
            dispatch(addPost(post));
            
            history.replace('/');

            // 업로드가 잘 끝났으면 설정해둔 미리보기 이미지를 null로 바꿈
            dispatch(imageActions.setPreview(null));
            
        }).catch((err) =>{  
            window.alert('포스트 작성 실패')
            console.log('작성 실패', err)
            
        }).catch((err) =>{ // 이미지 업로드에 문제가 있을 때
            window.alert('이미지 업로드 실패')
            console.log('이미지 업로드 에러',err)
        })
    })
})

Post.js

src 수정

<Image shape='rectangle' src={props.image_url}/>
profile
https://github.com/hyojin-k

0개의 댓글