body-parser
- 데이터 처리에 도움이 되는 라이브러리
- Post로 정보를 전송할 때 요청의 req.body로 받을 수 있음.
- express 버전 4부터 내장되어 있어 따로 설치가 필요X
- 단점, 멀티파트 데이터(이미지, 동영상, 파일 등) 처리X => multer 사용
파일 업로드 multer
: 클라이언트에서 서버로 데이터 전송을 할 때 사용, 파일 선택 버튼 {userfile: ' /png', title: ' '}
//설치
npm install multer
//app.js에 multer 불러오기
const multer = require('multer');
클라이언트 준비
form 태그에 enctype = "multipart/form-data"를 반드시 설정해야 동작한다.
<!-- 주의) multer 는 multipart 가 아닌 폼에서는 동작하지 않음!! -->
<form action="/upload" method="POST" enctype="multipart/form-data">
파일 업로드 경로 설정
const upload = multer({
dest: 'uploads/', // dest: 업로드할 파일 경로 지정
});
- dest : 파일 업로드하고 그 파일이 저장될 경로로 지정하는 속성
multer정리
single()
- 하나의 파일 업로드
req.file : 파일 하나
req. body : 나머지 정보
index.ejs
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile" /><br />
<input type="text" name="title" /><br />
<button type="submit">업로드</button>
</form>
app.js
// single(): 하나의 파일 업로드할 때
// single()의 매개변수: input 의 name과 일치시키기!
app.post('/upload', uploadDetail.single('userfile'), (req, res) => {
console.log(req.file); // 업로드한 파일 정보
console.log(req.body); // 폼에 입력한 정보
res.send('upload 완료~!!');
});
array()
- 여러 파일을 업로드할 때 사용, 하나의 요청 안에 여러 개의 파일이 존재할 때
req.files : 파일 n개
req.body: 나머지 정보
index.ejs
<form action="/upload/array" method="POST" enctype="multipart/form-data">
<!-- input type이 file일 때 multiple 속성을 추가하면 여러개 업로드 가능! -->
<input type="file" name="userfile" multiple /><br />
<input type="text" name="title" /><br />
<button type="submit">업로드</button>
</form>
app.js
app.post('/upload/array', uploadDetail.array('userfile'), (req, res) => {
console.log(req.files); // [ {}, {}, {} ]
console.log(req.body); // { title: 'xxx' }
res.send('여러개 파일 업로드 완료~!');
});
fields()
- 여러 파일 업로드할 때, 여러 개의 요청이 들어올 때
req.files : 파일 n개
req.body: 나머지 정보
index.ejs
<form action="/upload/fields" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile1" /><br />
<input type="text" name="title1" /><br />
<input type="file" name="userfile2" /><br />
<input type="text" name="title2" /><br />
<button type="submit">업로드</button>
</form>
app.js
app.post(
'/upload/fields',
uploadDetail.fields([{ name: 'userfile1' }, { name: 'userfile2' }]),
(req, res) => {
console.log(req.files); // { userfile1: [{}], userfile2: [{}] } 형태로 파일 정보 출력
console.log(req.body); // { title1: '망고', title2: '복숭아' }
res.send('각각 여러 파일 업로드 완료~!');
}
);
multer - 세부 설정
- storage : 저장할 공간에 대한 정보
- diskStorage : 파일을 디스크에 저장하기 위한 모든 제어 기능 제공
- destination : 저장할 경로
- filename : 파일명
- limits : 파일 제한
- fileSize : 파일 사이즈 제한
'[Study] BE > Node.js' 카테고리의 다른 글
[포스코x코딩온] Sequelize (0) | 2023.04.09 |
---|---|
[포스코x코딩온] MVC_MySQL (1) | 2023.04.09 |
[포스코x코딩온] Node.js MVC 구조 (0) | 2023.04.05 |
[포스코x코딩온] 동적 Form 전송 (0) | 2023.03.30 |
[포스코x코딩온] 웹 동작 방식 & Form 전송 (0) | 2023.03.28 |