node + multer + koa + react : 파일 업로드 받기

BABY CAT·2023년 1월 11일
0

react

목록 보기
4/4

프론트엔드

컴포넌트로 따로 만들고 임포트

post('http://127.0.0.1:3000/upload 이 부분에서
3000이 프론트인데 자동으로 백 서버로 이동한다

얼럿 기능 추가

import axios from 'axios';
import { useState } from 'react';

function Csh() {
  const [file, setFile] = useState('');

  const onChange = (e) => {
    setFile(e.target.files[0]);
  };
  const onSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();

    formData.append('file', file);

    try {
      const res = await axios.post('http://127.0.0.1:3000/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      alert(file.name + '  업로드 성공!');
      console.log(res)
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <>
      <form onSubmit={onSubmit}>
        <input type="file" onChange={onChange}  />
        <button type="submit">Upload</button>
      </form>
    </>
  );
}
export default Csh;

백엔드

서버 메인단에 넣는다

save 파일 이름 최적화

import Koa from 'koa';
import Router from 'koa-router';

const cors = require('@koa/cors');
const multer = require('@koa/multer');
const path = require('path');

//저장폴더, 저장파일이름 선언
const upload = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, __dirname + '/uploads/');  //저장 폴더
    },
    filename: function (req, file, cb) {
      /*리플레이스로 공백을 지우고 :을 .로 바꾼다*/
      cb(null,(((new Date().toLocaleString()).replace(/ /g,"")).replace(/:/g,"."))  + '.'+ path.basename(file.originalname)); //파일이름 선언하는 부분
    },  
  }),
});
//저장 후 파일이름 돌려주는 라우터
//upload.single('file') 여기서 저장
router.post('/upload', upload.single('file'), async (ctx, next) => {
  ctx.response.body = {
    filename: ctx.request.file.filename, // 백 서버에 저장된 파일이름 프론트로 보내주기
  };
});

0개의 댓글