상식닷컴
로그인
가입하기
2026년 상식닷컴 선정 식당 & 카페 리스트
2025년 2026년 신상 호텔 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요
일주일 식단표 어플
자동 일주일 식단표 어플
안드로이드
아이폰
주식 & 코인 차트의 신
1000만원으로 2000만원 만들기 프로젝트
수정하기 - Node.js에서 파일 업로드를 처리하는 방법은 무엇인가요?
닉네임
비밀번호
제목
내용
[이미지 업로드는 권한이 있는 사람만 가능. 하단 카톡으로 연락]
Node.js에서 파일 업로드를 처리하는 방법은 여러 가지가 있지만, 가장 일반적으로 사용되는 방법은 `multer`라는 <a href='https://sangseek.com/sangseeks/미들웨어/ko'>미들웨어</a>를 사용하는 것입니다. `multer`는 multipart/form-data 형식으로 전송된 파일을 처리하는 데 특화된 미들웨어로, <a href='https://sangseek.com/sangseeks/Express.js/ko'>Express.js</a>와 함께 사용됩니다. 아래에서는 Node.js에서 파일 업로드를 처리하는 방법을 단계별로 설명하겠습니다. 1. 프로젝트 설정 먼저, Node.js 프로젝트를 설정해야 합니다. 새로운 디렉토리를 만들고, 그 안에서 npm을 초기화합니다. ```bash mkdir file-upload-example cd file-upload-example npm init -y ``` 2. 필요한 패키지 설치 Express와 multer를 설치합니다. ```bash npm install express multer ``` 3. 기본 서버 설정 `server.js`라는 파일을 만들고, Express 서버를 설정합니다. ```javascript const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); const PORT = 3000; // 파일 저장 위치 및 파일 이름 설정 const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads/'); // 파일이 저장될 경로 }, filename: (req, file, cb) => { cb(null, Date.now() + path.extname(file.originalname)); // 파일 이름 설정 } }); // multer 설정 const upload = multer({ storage: storage }); // 업로드 폼을 제공하는 라우트 app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); // 파일 업로드를 처리하는 라우트 app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded.'); } res.send(`File uploaded successfully: ${req.file.filename}`); }); // 서버 시작 app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); ``` 4. HTML 업로드 폼 만들기 `index.html` 파일을 생성하고, 파일 업로드를 위한 간단한 HTML 폼을 작성합니다. ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload</title> </head> <body> <h1>File Upload</h1> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file" required> <button type="submit">Upload</button> </form> </body> </html> ``` 5. 파일 업로드 디렉토리 생성 파일이 업로드될 디렉토리를 생성합니다. `uploads`라는 이름의 폴더를 만들어야 합니다. ```bash mkdir uploads ``` 6. 서버 실행 서버를 실행합니다. ```bash node server.js ``` 브라우저에서 `http://localhost:3000`에 접속하면 파일 업로드 폼이 나타납니다. 파일을 선택하고 업로드 버튼을 클릭하면, 선택한 파일이 `uploads` 폴더에 저장됩니다. 7. 추가적인 설정 - 파일 크기 제한 : `multer`를 사용할 때 파일 크기를 제한할 수 있습니다. 예를 들어, 1MB로 제한하려면 다음과 같이 설정할 수 있습니다. ```javascript const upload = multer({ storage: storage, limits: { fileSize: 1 * 1024 * 1024 } // 1MB }); ``` - 파일 형식 제한 : 특정 파일 형식만 허용하고 싶다면, `fileFilter` 옵션을 사용할 수 있습니다. ```javascript const upload = multer({ storage: storage, fileFilter: (req, file, cb) => { const filetypes = /jpeg|jpg|png|gif/; // 허용할 파일 형식 const mimetype = filetypes.test(file.mimetype); const extname = filetypes.test(path.extname(file.originalname).toLowerCase()); if (mimetype && extname) { return cb(null, true); } cb('Error: File upload only supports the following filetypes - ' + filetypes); } }); ``` 8. 결론 Node.js에서 파일 업로드를 처리하는 것은 `multer`와 같은 미들웨어를 사용하면 매우 간단합니다. 위의 예제는 기본적인 파일 업로드 기능을 구현하는 방법을 보여주며, 필요에 따라 추가적인 기능을 구현할 수 있습니다. 파일 업로드는 웹 애플리케이션에서 매우 일반적인 기능이므로, 이를 잘 이해하고 활용하는 것이 중요합니다.
이용안내
커뮤니티 이용안내
×
- 게시한 게시글로 발생하는 문제는 게시자에게 책임이 있습니다.
- 게시글이 타인/타업체의 저작권을 침해할 경우 모든 책임은 게시자에게 있습니다. 게시자가 모든 손해를 부담해야 합니다.
- 상식닷컴 운영자는 게시자와 상의하지 않고 게시글을 수정 또는 삭제할 수 있습니다.
- 상식닷컴 운영자는 깨끗한 커뮤니티 공간을 만드는 것이 1순위입니다.
수정하기
취소하기