본문 바로가기

내일배움캠프 노드 4기/Today I Learned

Node.js 파일 업로드 하기 - multer , <form enctype=" ">

모듈 설치하기

npm install --save multer

multer 사용 선언하기

const multer = require("multer");

 

경로 및 파일 이름 설정

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./assets/uploads/"); // 파일 경로 설정
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + "-" + Date.now()); 
  }, //필드네임인 img와 현재 시각을 파일 이름으로 설정했다
});
const upload = multer({ storage: storage });

실제로 작동하는 부분

app.post("/upload", upload.single("img"), (req, res, next) => {
  res.status(200).send(req.file);
});

프론트

<form action='upload' method='post' enctype="multipart/form-data">
      <input type='file' name='img'>
      <input type='submit'>
    </form>

파일 선택 하고 제출 눌렀을 시

한글은 깨지는 모습이다

./assets/uploads 폴더에 파일이 들어가 있는 모습


<form> 태그의 enctype 속성      enctype = 인코딩 타입

<form enctype="속성값">

http://www.tcpschool.com/html-tag-attrs/form-enctype

'내일배움캠프 노드 4기 > Today I Learned' 카테고리의 다른 글

jest 테스트 코드  (0) 2023.01.09
Node.js ejs에서 js객체, 배열 전달하기  (0) 2023.01.06
ERD 작성하기 - 관계  (0) 2022.12.30
socket.io 서버에 적용하기  (1) 2022.12.29
socket.io  (0) 2022.12.29