1. Multer
nodeJS 서버에 파일을 업로드 할 때 사용하는 라이브러리
npm install multer
2. 간단한 파일업로드 HTML 폼 만들기
<!DOCTYPE html>
<html>
<head>
<title>Multer Example</title>
</head>
<body>
<h1>Upload a file</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
3. app.js에 파일 업로드 설정하기
업로드 파일은 'uploads/' 폴더에 저장하고 파일 업로드가 성공적으로 완료되면, 클라이언트에게 업로드 성공 응답하기
// 필요한 모듈을 불러옵니다.
const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;
// Multer 설정: 업로드된 파일을 'uploads/' 폴더에 저장
const upload = multer({ dest: 'uploads/' });
// 정적 파일을 제공할 디렉토리를 설정
app.use(express.static('public'));
// '/upload' 라우트를 설정하고 multer 미들웨어를 사용
// multer의 upload.single('file') 함수로 'file' 이라는 이름의 단일 파일 처리
app.post('/upload', upload.single('file'), (req, res) => {
console.log(`File uploaded: ${req.file.originalname}`);
res.status(200).send('File uploaded successfully.');
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
4. 사용자 정의 옵션 설정하기
npm install fs
npm install path
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
// 사용자 정의 스토리지 엔진 생성
const storage = multer.diskStorage({
// 파일이 저장되는 위치를 설정 (file: 업로드된 파일의 정보, cb: 콜백 함수)
destination: (req, file, cb) => {
// 업로드 폴더 경로 지정
const uploadPath = 'uploads/';
// 폴더가 없으면 폴더를 생성
if (!fs.existsSync(uploadPath)) {
fs.mkdirSync(uploadPath);
}
// 콜백 함수를 호출하여 업로드 경로를 전달
cb(null, uploadPath);
},
// 저장할 파일 이름 지정
filename: (req, file, cb) => {
// 콜백 함수를 호출하여 변경된 파일 이름을 전달
// file.fieldname: 폼 필드의 이름, Date.now(): 현재 시간 (밀리초), path.extname(file.originalname): 원본 파일의 확장자
// 파일 이름 예: file-1633959266884.jpg
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// 파일 확장자 필터 정의
const fileFilter = (req, file, cb) => {
// 허용되는 파일 확장자
const allowedFileTypes = ['.jpg', '.jpeg', '.png'];
// 파일의 확장자와 허용된 확장자를 비교
if (allowedFileTypes.includes(path.extname(file.originalname))) {
cb(null, true);
} else {
cb(new Error('Invalid file type')); // 유효하지 않은 파일 형식
}
};
// Multer 설정: 사용자 정의 스토리지를 설정하고 파일 크기 제한 및 파일 필터링 적용
const upload = multer({
storage: storage,
limits: { fileSize: 1024 * 1024 * 2 }, // 2MB 크기 제한
fileFilter: fileFilter
});
/* 3단계 코드와 동일 */
const app = express();
const port = 3000;
app.use(express.static('public'));
app.post('/upload', upload.single('file'), (req, res) => {
console.log(`File uploaded: ${req.file.filename}`);
res.status(200).send('File uploaded successfully.');
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
원하는 옵션을 설정하여 서비스에 맞는 파일 업로드를 구현하면 됩니다.
반응형
'개발정리 (nodeJS)' 카테고리의 다른 글
[nodeJS] body-parser로 JSON 파싱하기 (0) | 2023.06.17 |
---|---|
[nodeJS] Axios로 HTTP 요청하기 (0) | 2023.06.16 |
[nodeJS] Moment로 날짜, 시간 포맷 바꾸기 (0) | 2023.06.14 |
[nodeJS] Node.js 개발에 흔히 사용되는 라이브러리 5개 (0) | 2023.06.13 |
[nodeJS] nodemailer로 메일 보내기 (0) | 2023.06.12 |