inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[리뉴얼] React로 NodeBird SNS 만들기

input 파일 업로드시 다른정보는 넘어가는데 file정보가 넘어가지 않는 현상

348

허성진

작성한 질문수 5

0

안녕하세요 개인작업중에 질문이있습니다.

서버와 통신중 백엔드 서버에 게시글 올리는 기능을 만드는데 다른 정보들은 넘어가는데 이미지 파일만 넘어가지 않는 현상이 있어서 질문드립니다.

통신 방법과 이미지 데이터 바꾸기 등을 하여도 넘어가지 않습니다.

 

코드입니다 

import React, { useCallback, useEffect, useRef, useState } from 'react';
import Router from 'next/router';

import MainLayout from '../components/MainLayout';
import style from '../styles/css/upload.module.css';
import useInput from '../hooks/useInput';
import { useDispatch, useSelector } from 'react-redux';
import {
ADD_POST_REQUEST,
LOAD_POSTS_REQUEST,
UPLOAD_IMAGES_REQUEST,
} from '../reducers/post';
import { POST_CARD } from '../reducers/menu';
import axios from 'axios';

const Home = () => {
const dispatch = useDispatch();
const { me } = useSelector((state) => state.user);
const { mainPosts, addPostDone, imagePaths } = useSelector(
(state) => state.post,
);

const [photoToAddList, setPhotoToAddList] = useState([]);
const [content, onChangeContent, setContetn] = useInput();
const [notice, onChangeNotice, setNotice] = useInput(false);

const ref = useRef();
const handleResizeHeight = useCallback(() => {
if (ref === null || ref.current === null) {
return;
}
ref.current.style.height = '20px';
ref.current.style.height = ref.current.scrollHeight + 'px';
}, []); //댓글창 크기 자동조절

useEffect(() => {
if (!me) {
Router.push('/');
}
}, [me]);

const checkboxClick = useCallback(() => {
setNotice((prev) => !prev);
}, [notice]);

const imageInput = useRef();
const onClickImageUpload = useCallback(() => {
imageInput.current.click();
}, [imageInput.current]);

// 이미지 파일 변수에 저장
const handleImage = useCallback(
(e) => {
const temp = [];
const photoToAdd = e.target.files;
for (let i = 0; i < photoToAdd.length; i++) {
console.log(photoToAdd);
temp.push({
id: photoToAdd[i].name,
file: photoToAdd[i],
url: URL.createObjectURL(photoToAdd[i]),
});
}
if (temp.length > 10) {
return alert('최대개수 10개가 넘어갔습니다');
}
if (temp.length + photoToAddList.length > 10) {
return alert('최대개수 10개가 넘어갔습니다');
}
if (photoToAddList.length > 10) {
return alert('최대개수 10개가 넘어갔습니다');
}

setPhotoToAddList(temp.concat(photoToAddList));
// setPhoto(temp.push(temp.forEach((v) => v)));
},
[photoToAddList],
);

const onRemove = useCallback(
(deleteUrl) => {
setPhotoToAddList(photoToAddList.filter((v) => v.url !== deleteUrl));
},
[photoToAddList],
);

 

const upLoadFormClick = useCallback(
(e) => {
e.preventDefault();
if (!photoToAddList.length > 0) {
alert('이미지를 등록해주세요');
return;
}
if (!content) {
alert('내용을 등록해주세요');
return;
}

dispatch({
type: ADD_POST_REQUEST,
data: {
bo_writer: me.id,
bo_content: content,
bo_image: photoToAddList,
},
});
dispatch({
type: LOAD_POSTS_REQUEST,
data: {
mem_id: me?.id,
},
});
setTimeout(() => {
if (addPostDone) {
Router.push('/');
dispatch({
type: POST_CARD,
});
}
}, 1000);
},
[photoToAddList, content, addPostDone],
);

return (
<>
<MainLayout>
<div style={{ paddingTop: '24px' }}></div>
<section className={style.a}>
<article className={style.maxWidth}>
<form
encType="multipart/form-data"
onSubmit={upLoadFormClick}
className={style.upLoadForm}
>
{me?.grade === 'admin' && (
<div>
<span>공지</span>
<input
name="mem_flag"
type="checkbox"
value={notice}
onClick={checkboxClick}
// required
/>
</div>
)}
<div className={style.imageBox}>
{/* /분리 */}
<ul>
{photoToAddList
? photoToAddList.map((v) => {
return (
<li key={v.url}>
<div
className={style.remove}
onClick={() => onRemove(v.url)}
>
x
</div>
<img
src={v.url}
style={{
backgroundImage: `url(${v.url})`,
}}
/>
</li>
);
})
: null}
<li onClick={onClickImageUpload}>
<div className={style.imageInput}>
<img src="/icon/addphoto.svg" className={style.addImg} />
</div>
</li>
</ul>
</div>

<input
name="bo_image"
type="file"
accept="image/jpg, image/jpeg, image/png"
ref={imageInput}
onChange={handleImage}
hidden
multiple
required
/>

<div className={style.textInput}>
<textarea
name="bo_content"
type="text"
placeholder="문구를 입력해주세요"
ref={ref}
onInput={handleResizeHeight}
onChange={onChangeContent}
maxLength={140}
required
/>
<button>게시</button>
</div>
</form>
</article>
</section>
<div style={{ paddingBottom: '44px' }}></div>
</MainLayout>
</>
);
};

Home.propTypes = {};

export default Home;

 

// 게시물 등록하기
function addPostAPI(data) {
console.log(data, 'data');
return axios.post(
`/board/insert.do?bo_writer=${data.bo_writer}&bo_content=${data.bo_content}&bo_image=${data.bo_image}`,
data,
);
}

function* addPost(action) {
try {
const result = yield call(addPostAPI, action.data);
console.log(result);
yield put({
type: ADD_POST_SUCCESS,
data: result.data,
});
} catch (error) {
console.error(error);
yield put({
type: ADD_POST_FAILURE,
data: error.response.data,
});
}
}

 

 

 

react nodejs express redux Next.js

답변 1

0

제로초(조현영)

Internal Server Error면 서버쪽 콘솔에서 에러메시지 확인하셔야 합니다.

0

허성진

서버 쪽은 다른분이 만들고있는데 뭐라고 전해야할까요? 

프론트쪽도 손봐야할부분이 있을까요? 콘솔 리덕스에 보면 파일이 안들어가 있는부분에서요

0

제로초(조현영)

서버쪽에서 해당 요청 시 발생하는 에러 확인해달라고 해야 합니다. 그리고 요청 시 데이터를 뭐를 어떻게 보냈는지 서버쪽에 알려주셔야 합니다.

넥스트 버젼 질문

0

90

2

로그인시 401 Unauthorized 오류가 뜹니다

0

104

1

무한 스크롤 중 스크롤 튐 현상

0

192

1

특정 페이지 접근을 막고 싶을 때

0

116

2

createGlobalStyle의 위치와 영향범위

0

102

2

인라인 스타일 리렌더링 관련

0

97

2

vsc 에서 npm init 설치시 오류

0

157

2

nextjs 15버전 사용 가능할까요?

0

166

1

화면 새로고침 문의

0

129

1

RTK에서 draft, state 차이가 있나요?

0

160

2

Next 14 사용해도 될까요?

0

455

1

next, node 버전 / 폴더 구조 질문 드립니다.

0

359

1

url 오류 질문있습니다

0

214

1

ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out

0

391

1

sudo certbot --nginx 에러

0

1293

2

Minified React error 콘솔에러 (hydrate)

0

477

1

카카오 공유했을 때 이전에 작성했던 글이 나오는 버그

0

255

1

프론트서버 배포 후 EADDRINUSE에러 발생

0

337

1

npm run build 에러

0

525

1

front 서버 npm run build 중에 발생한 에러들

0

399

1

서버 실행하고 브라우저로 들어갔을때 404에러

0

350

2

css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.

0

290

1

팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.

0

249

2

해시태그 검색에서 throttle에 관해 질문있습니다.

0

206

1