JavaScript의 fileReader를 사용하여 파일 객체의 내용물을 읽어와서 미리보기를 생성한다
Upload.js
const selectFile = (e) =>{
// 파일리더 객체 만들기
const reader = new FileReader();
const file = fileInput.current.files[0];
// 어떤 것을 읽고싶은지 파일 객체 넣기 (내장함수 사용)
reader.readAsDataURL(file);
// 읽기가 끝나면 발생하는 이벤트 핸들러
reader.onloadend = () =>{
console.log(reader.result)
// 결과 값을 PostWrite에서 사용하기 위해 리덕스로 보내줘야함
}
}
image.js
const SET_PREVIEW = 'SET_PREVIEW'
const setPreview = createAction(SET_PREVIEW, (preview) =>({preview}));
const initialState = {
image_url:'',
uploading: false,
preview:null,
}
[SET_PREVIEW] : (state, action) => produce(state, (draft) =>{
draft.preview = action.payload.preview;
})
const actionCreators = {
uploadImage,
uploadImageFB,
setPreview
}
PostWrite.js
const preview = useSelector((state)=> state.image.preview);
<Image shape='rectangle' src={preview? preview : 'http://via.placeholder.com/400x300'}/>
Upload.js
reader.onloadend = () =>{
dispatch(imageActions.setPreview(reader.result));
}