Node.js

[Node.js] Multer

JungCw 2024. 11. 20. 09:11

Multer

multer는 express에서 파일 업로드를 위한 미들웨어이다.

 

다중 파일 업로드가 가능하며 일반 텍스트와 파일 데이터 두 가지를 동시에 처리하는 것도 가능하다.

 

 

설치.

npm i multer

 

이미지 파일을 저장하는 예시로 보이겠다.

 

서버 측 코드 파일에서 index.js 파일 등에 한번에 해버려도 좋지만, 가독성을 위해 분리해두었다.

 

<uploadImgConfig.js>

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

const uploadPath = path.join(__dirname, '업로드할 폴더 위치');
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadPath);	//업로드 위치
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`);		//고유 파일 이름 생성
  }
});

//미들웨어 생성
const upload = multer({ storage: storage });

module.exports = upload;

 

이런식으로 multer 설정 파일을 생성해준다.

 

router.post('/upload_image', upload.single('image'), (req, res) => {
    if (!req.file) {
        return res.status(400).send('No file uploaded.');
    }
    const imagePath = `/img/${req.file.filename}`;  // 클라이언트에서 접근 가능한 경로
    res.json({ img_src: imagePath });
});

 

이제 엔드포인트에 맞춰 서버에 이미지 파일을 저장하고 클라이언트 측에서 접근 가능한 경로를 반환한다.

이렇게 하면 클라이언트 측에서는 img_src로 간단히 접근이 가능하다.