이미지와 같은 파일을 저장하는 클라우드 저장소
write: if request.auth != null;
firebase.js
import 'firebase/storage';
const storage = firebase.storage();
export {auth, apiKey, firestore, storage};
Upload.js
const Upload = (props) =>{
const fileInput = React.useRef();
const selectFile = (e) =>{
console.log(e.target.files[0]);
// 위 아래 콘솔이 같은 값
console.log(fileInput.current.files[0]);
}
return(
<React.Fragment>
<input type='file' onChange={selectFile} ref={fileInput}/>
</React.Fragment>
)
}
import {storage} from './firebase'
파일 업로드 - firebase docs 참고
파일 이름을 포함한 ref 참조를 만들기
const uploadFB = () =>{
let image = fileInput.current.files[0];
// storage에서 만든 폴더(images)
const _upload = storage.ref(`images/${image.name}`).put(image);
// 무엇을 업로드 했는지 확인
_upload.then((snapshot) =>{
console.log(snapshot);
})
}
_upload.then((snapshot) =>{
console.log(snapshot);
snapshot.ref.getDownloadURL().then((url) =>{
console.log(url)
})
})
image.js
import {createAction, handleActions} from 'redux-actions';
import {produce} from 'immer';
import {storage} from '../../shared/firebase';
// 업로드 중인지 아닌지 알게해주는 액션
const UPLOADING = 'UPLOADING';
// 실제로 파일 업로드 하는 액션
const UPLOAD_IMAGE = 'UPLOAD_IMAGE';
const uploading = createAction(UPLOADING, (uploading) => ({uploading}));
const uploadImage = createAction(UPLOAD_IMAGE, (image_url)=>({image_url}));
const initialState = {
image_url:'',
uploading: false,
}
const uploadImageFB = (image) =>{
return function(dispatch, getState, {history}){
// 업로드 시작하기 전에
dispatch(uploading(true))
const _upload = storage.ref(`images/${image.name}`).put(image);
// 무엇을 업로드 했는지 확인
_upload.then((snapshot) =>{
console.log(snapshot);
// stroage에 올린 이미지 링크 받아오기
snapshot.ref.getDownloadURL().then((url) =>{
console.log(url)
// 업로드 이미지 기록
dispatch(uploadImage(url))
});
}).catch(err =>{
dispatch(uploading(false));
})
}
}
export default handleActions({
[UPLOAD_IMAGE]: (state, action) => produce(state, (draft) =>{
// image url 고치기
draft.image_url = action.payload.image_url;
draft.uploading = false;
}),
[UPLOADING] : (state, action) => produce(state, (draft) =>{
// 업로딩 상태 바꾸기
draft.uploading = action.payload.uploading;
})
}, initialState);
const actionCreators = {
uploadImage,
uploadImageFB,
}
export {actionCreators}
configureStore.js
import Image from './modules/image';
const rootReducer = combineReducers({
user: User,
post: Post,
image: Image,
router: connectRouter(history),
});
Upload.js
import {useDispatch, useSelector} from 'react-redux';
import { actionCreators as imageActions } from "../redux/modules/image";
const is_uploading = useSelector(state => state.image.uploading);
const uploadFB = () =>{
if(!fileInput.current || fileInput.current.files.length === 0){
window.alert('파일 선택');
return;
}
dispatch(imageActions.uploadImageFB(fileInput.current.files[0]))
}
<input type='file' onChange={selectFile} ref={fileInput} disabled={is_uploading} />