이미지 파일을 받아서 지정 폴더에 저장하기
const { v4: uuid } = require("uuid");
const mime = require("mime-types");
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, "./uploads"), //저장경로
filename: (req, file, cb) => cb(null, `${uuid()}.${mime.extension(file.mimetype)}`),
}); // 파일명이 중복되지 않도록 고유성이 보장되는 id를 통하여(uuid) 저장
const upload = multer({ storage,
limits:{
fileSize: 1024 * 1024 * 10, // 파일 사이즈 제한하기
}
});
router.post("/posts", upload.single("imageTest"), async (req, res) => { //upload.single(imageTest)의 'img'는 formData 의 key값 / img key 의 value값을 서버의 지정된 폴더에 저장.
const { title, content } = req.body;
const nickname = '닉네임6'; // 유저정보 api와 아직 합치지 않아, 임의값 지정함. (req.body로 받을예정)
const imageName = req.file.filename;
const imagelocation = req.file.path;
const createPosts = await Posts.create({ title: title, imageUrl: imageName,
content: content, nickname: nickname, imagelocation: imagelocation })
console.log(imagelocation)
console.log(req.file)
res.json({ posts: createPosts })
})
하나의 파일만 받기때문에 upload.single로 받았다.
req.file 에는 아래의 정보를 포함하고있다.
나는 이번 미니프로젝트에서 이미지파일을 저장하고 불러오기위해 mongodb에 파일명을 string값으로 저장하고, 폴더에 파일을 저장했다. 불러올때엔 db의 파일명 클라이언트에 보내고 클라이언트에서 < img src >를 사용할 수 있도록 할 예정이다.