
const multer = require("multer");
const upload = multer({ storage: storage });
var corsOptions = {
origin: "http://localhost:3000",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
credentials: true
};
app.use([
express.static("public"),
express.json(),
cors(corsOptions),
upload.array("files")
]);
multer 라이브러리
var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "public/"); }, filename: function (req, file, cb) { let ext = file.originalname.split("."); ext = ext[ext.length - 1]; cb(null, `${Date.now()}.${ext}`); } });
diskStorage({})
이미지를 어디다가 저장할지 정하는 함수 (하드디스크)
memoryStorage({})
이미지를 어디다가 저장할지 정하는 함수 (램/휘발성)
destination
이미지 저장 경로
cb(null, ' 이미지 저장 경로 ' )// 여기에 맞춰서 폴더 생성해줘야 함destination: function (req, file, cb) { cb(null, "public/"); }
filename
파일명 설정
cb(null, ' file.originalname' )// 기본 오리지널 파일이름으로 저장
cb(null, ' __ ' );// 어떤 이름으로 저장할지 지정filename: function (req, file, cb) { let ext = file.originalname.split("."); ext = ext[ext.length - 1]; cb(null, `${Date.now()}.${ext}`); }
const upload = multer({ storage: storage });위에서 세팅했던 변수를 multer({storage : 변수명 }) 으로 세팅후에 사용
app.post('/upload', upload.single , function(req,res){ }) app.post('/upload', upload.array, function(req,res){ })여러개 업로드 - array('키', 최대파일개수)
req.files에 정보가 담긴다
단일 업로드 - single('img') // 폼 속성명이 img이거나 폼 태그의 인풋의 name이 img인 파일을 한개만 받는다
그 외에도
filefilter으로 파일 확장자를 거를 수 있고
limits 로 파일 사이즈도 제한을 둘 수 있다.
프로젝트를 진행하면서 에디터 구현에 필요한 multer 라이브러리를 사용해 보았는데,
코드적인 부분에서 이해가 되지 않는 부분이 많아 추가적으로 공부하여 정리해보았다.