[Node.js] react와 연동해서 사진 들고오기

오버·2022년 7월 8일
0

Node.js Study

목록 보기
15/22

시작하기 전에...

네, 오늘은 제목에도 나와 있듯이 react와 연동하여 사진 들고오기를 해보겠습니다.

react

자 그러면 react부터 시작해봅시다.

일단 file 데이터를 받아오기 위해서는

<input type="file" id="file-input" name="imageFile" onChange={handleChangeFile} />

input의 type을 file로 지정하면 될 일입니다.

사실 이 정도는 누구나 하는거고

그 다음부터가 매우 중요합니다.

저희는 이 file의 value를 파싱해서 서버로 post 해줘야합니다.

그래서 구글링을 해보니 다들 file을 들고올 때

event.target.files[0];

이라는 명령어를 사용하여 들고오더라고요.

근데 저는 이상하게 이렇게 하면 안되고

const upload = document.getElementById("file-input").files[0]

이런 식으로 선언을 해야만 file 데이터가 들고와지더라고요.

저도 왜 그런지는 모르겠습니다. 왜 저건 되고 위에는 안되는지를 모르겠어요.

아무튼 react의 총 코드는 이렇습니다.

import React from 'react'
import '../CSS/Login.css'
import axios from "axios";
import { useNavigate } from 'react-router-dom'
export default function Login() {
  const navigate = useNavigate();
  const submit = async (event) => {
    event.preventDefault();
    const upload = document.getElementById("file-input").files[0]
    const formData = new FormData()
    formData.append('imageFile', upload)
    await axios({
      url: 'http://localhost:8080/image/upload',
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.error(error);
      });
    navigate("/");
  }
  return (
    <div className='div--Login'>
      <form className='form--Login' method="post" enctype="multipary/form-data">
        <input type="file" id="file-input" name="imageFile" />
        <input type='submit' name='submit' value='Submit' onClick={submit}/>
      </form>
    </div>
  )
}

input 데이터를 폼으로 전송하고 post 데이터를 쏴 서버와 연동을 합니다.

다음으로 node.js 입니다.

var express = require('express');
var router = express.Router();
const path = require('path');
var multer = require('multer');
const upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, 'public/images/');
        },
        filename: function (req, file, cb) {
            var newFileName = new Date().valueOf() + path.extname(file.originalname)
            cb(null, newFileName);
        }
    }),
});
router.get('/',(req, res) => {
    res.status(200).json({ massage:'이미지 화면에 들어오신 것을 확인하십니다.' });
})
router.post('/upload', upload.single('imageFile'), (req, res) => {
    console.log('hi')
    let path = './images/' + req.file.filename;
    console.log(path)
    res.status(200).json({image_path: path});
});
module.exports = router;

제가 처음에 multer라는 모듈을 소개드린 적이 있었습니다.

그 multer 모듈을 이용하여

사진을 저장할 곳을 지정하고

filename을 직접 커스텀했습니다.

그리고 post에서
hi를 출력한 이유는 연결이 잘 됬는지 확인하기 위함이고
path라는 변수를 이용하여 image가 곳을 저장하고
json 데이터로 클라이언트에게 보냈습니다.

자 그럼 결과로 살펴볼까요?

결과 확인

사진을 전송하면~~

images 폴더에 숫자로 된 사진이 보이실텐데 그 사진이 제가 커스텀한 사진이고 콘솔 창에도 경로가 문제 없이 뜹니다. 만사 OK!

마치며

진짜 file 전송 하는 게 너무 어려운 것 같습니다. 너무 불편하기도 하고...

다들 event.target.files[0]로 하는데 저는 안되고...

그리고 한 가지 중요한 점은 절대로 onSubmit으로 함수를 지정하면 안 된다는 점입니다.

이런 x친 react가 onSubmit을 해버리면 금붕어가 되어버렸는지 값을 못 들고옵니다.

아무튼 이번 포스팅은 여기서 마치겠습니다. Bye Bye

profile
개발자

0개의 댓글