1. multer이란?
파일 업로드를 위해 사용되는 노드의 미들웨어이다.
2. fs 모듈 사용하여 파일 있는지 확인하기
fs는 노드 js에 들어있는 모듈로 file system의 약자이다. 서버의 파일/폴더에 접근할 수 있는 함수들이 들어있다.
fs.readdirSync() 함수로 폴더가 존재하는지 확인하고, 없으면 fs.mkdirSync() 함수로 폴더를 생성해준다.
try {
fs.readdirSync('uploads');
} catch (error) {
console.log('uploads 폴더가 없어 uploads 폴더를 생성합니다.');
fs.mkdirSync('uploads');
}
3. multer module 불러오기
const multer = require('multer');
4. multer module 사용하기
const upload = multer({
storage : multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
const ext = path.extname(file.originalname);
cb(null, path.basename(file.originalname, ext) + new Date().valueOf() + ext);
},
}),
limits: {fileSize : 5 * 1024 * 1024},
});
➡️
upload: 미들웨어를 만드는 객체 (storage 속성과 limits 속성을 부여할 수 있음.)
storage: 파일 저장 방식과 경로, 파일명 등을 설정
diskStorage: 이미지가 서버 디스크에 저장되도록 함, diskStorage의 destination 메소드로 저장 경로를 uploads/로 지정 (fs.mkdirSync())로 만들어둔 경로
파일명: filename 메소드로 기존 이름에 업로드 날짜를 더하여 파일명 중복을 방지
limits: 최대 이미지 파일 용량 허용치
cb: callback 함수 (다른 함수가 실행을 끝낸 후 실행되는 함수)
'Backend Study > Node.js' 카테고리의 다른 글
call back 함수 (1) | 2022.09.02 |
---|---|
Node.js 내장 모듈 사용하기 (0) | 2022.08.04 |
Node.js Process (0) | 2022.08.04 |
Node.js 모듈 이용하기 (0) | 2022.08.04 |
Node.js 설치하기 (0) | 2022.08.03 |