diff --git a/backend/src/api/index.js b/backend/src/api/index.js index 6de07f5..3974f8e 100644 --- a/backend/src/api/index.js +++ b/backend/src/api/index.js @@ -1,4 +1,5 @@ -import { Router } from "express"; +import { Router, static as serveStatic } from "express"; +import express from "../loaders/express"; import { accounts, mariadbTest, board, career, image } from "./routes"; const app = Router(); @@ -8,6 +9,7 @@ app.use("/accounts", accounts); app.use("/board", board); app.use("/career", career); app.use("/", mariadbTest); +app.use(serveStatic("public")); app.use("/image", image); export default app; diff --git a/backend/src/api/routes/image.js b/backend/src/api/routes/image.js index 8deb2bd..8fedc88 100644 --- a/backend/src/api/routes/image.js +++ b/backend/src/api/routes/image.js @@ -1,7 +1,13 @@ import { Router } from "express"; +import { uploadAvatar } from "../../loaders/multer"; const router = Router(); +router.post("/upload", uploadAvatar, (req, res) => { + const { fieldname, originalname, encoding, mimetype, destination, filename, path, size } = req.file + const { name } = req.body; + console.log(destination, filename, size); +}); export default router; diff --git a/backend/src/loaders/multer.js b/backend/src/loaders/multer.js index a17c095..f6bc754 100644 --- a/backend/src/loaders/multer.js +++ b/backend/src/loaders/multer.js @@ -2,41 +2,43 @@ import multer from "multer"; import path from "path"; import dotenv from "dotenv"; import Logger from "./logger"; +import fs from "fs"; dotenv.config(); -const IMAGE_PATH = '../../public/images' +const IMAGE_PATH = path.resolve('./public/images'); try { fs.readdirSync(IMAGE_PATH); } catch (error) { Logger.error('❌Not exist direcotry'); - fs.mkdirSync(IMAGE_PATH); + fs.mkdirSync(IMAGE_PATH, { recursive: true }); } const storage = multer.diskStorage({ destination: function (req, file, cb) { - cb(null, '../../public/images'); + cb(null, IMAGE_PATH); }, filename: function (req, file, cb) { - const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) - cb(null, file.fieldname + '-' + uniqueSuffix) + const uniqueSuffix = Date.now() + '_' + Math.round(Math.random() * 1E9) + cb(null, file.fieldname + '_' + uniqueSuffix + '.' + file.mimetype.split("/")[1] ?? ""); } }) /** * 유저 프로필 사진 업로드에 대한 multer 세팅 */ -const multerAvatar = multer({ +const multerAvatar = multer({ storage: storage, - limits: {fileSize:5*1024*1024}, // 파일 크기 5MB 제한 - fileFilter: function(req,file,done){ // 이미지 형식 파일만 필터링 - if(file.mimetype.lastIndexOf('image')>-1){ - done(null,true); // 파일 허용 - }else { - done(null,false); // 파일 거부 + limits: { fileSize: 5 * 1024 * 1024 }, // 파일 크기 5MB 제한 + fileFilter: function (req, file, done) { // 이미지 형식 파일만 필터링 + if (file.mimetype.lastIndexOf('image') > -1) { + done(null, true); // 파일 허용 + } else { + done(null, false); // 파일 거부 } - }.single('file') + }, + }); export const uploadAvatar = multerAvatar.single('avatar'); // 'avatar'는 front에서 받아오는 field 명