내배캠 51일차

·2023년 1월 3일
0

내일배움캠프

목록 보기
54/142
post-thumbnail

multer

multer.js

const multer = require("multer");
const path = require("path");

// const fileFilter = (req, file, cb) => {
//   //확장자 필터링
//   if (
//     file.mimetype === "image/png" ||
//     file.mimetype === "image/jpg" ||
//     file.mimetype === "image/jpeg"
//   ) {
//     //해당하는 mimetype만 받겠다는 의미
//     cb(null, true);
//   } else {
//     req.fileValidationError =
//       "jpg, jpeg, png, gif, webp 파일만 업로드 가능합니다!";
//     cb(null, false);
//   }
// };

const upload = multer({
  storage: multer.diskStorage({
    //폴더위치 지정
    destination: (req, file, done) => {
      done(null, "./views/images");
    },
    filename: (req, file, done) => {
      const ext = path.extname(file.originalname);
      // aaa.txt => aaa+&&+129371271654.txt
      const fileName = path.basename(file.originalname, ext) + Date.now() + ext;
      done(null, fileName);
    },
  }),
  // fileFilter: fileFilter,
  limits: { fileSize: 30 * 1024 * 1024 },
});

module.exports = { upload };

=> 폴더 위치와 파일을 저장할 때 이름형식, 파일 크기를 지정해주는 코드!
(확장자 필터링은 안 써서지길래 주석 처리함...!
더 자료 찾아봐야함!)

routes

포스트 기능 api의 route에 multer.js를 연결해주어야함!
=> 이번 프로젝트 같은 경우에는 laundry.routes.js

const { upload } = require("../multer.js");

router.post(
  "/apply",
  upload.single("file"),
  authMiddleware,
  laundryController.createApply
);
profile
개발자 꿈나무

0개의 댓글