간단하게 파일을 input으로 입력받아서 전송하면 multer 모듈을 이용해서 특정폴더에 저장하고 그 파일을
서비스 할 수 있게 하는 기능을 구현.

필히 multer 모듈을 설치해야 함.
커멘드 창 열고 프로젝트 폴더에서 다음 명령을 실행해서 설치 가능.
npm install --save multer
[소스코드 : app_file.js (일부내용 생략)]
// 익스프레스 설정
var express = require('express');
var app = express();
// POST 전송을 위한 body-parser 설정 -> bodyParser의 Install 이 먼저 선행되어야 함 (npm install --save bodyparser)
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
// 파일업로드 처리를 위한 multer 및 폴더 설정 -> multer 모듈 인스톨 필요 (npm install --save multer)
var multer = require('multer');
var _storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, 'uploads/');
// 콜백함수를 사용해서 다음과 같이 파일형식이나 확장자에 따라서 저장폴더를 나누는 것이 가능
// if (file==img) {cb(null, 'uploads/img');} else if (file==txt) {cb(null, 'uploads/txt');}
},
filename: function(req, file, cb){
cb(null, file.originalname);
}
});
var upload = multer({ storage:_storage });
// 파일 업로드 페이지
app.get('/upload', function(req, res){
res.render('upload');
});
// 파일 업로드 버튼 눌렀을 때 처리(미들웨어로 파일을 HTTP헤더에 포함해서 처리 with 파일태그 이름 userfile)
app.post('/upload', upload.single('userfile'), function(req, res){
console.log(req.file);
res.send('uploaded success!' + req.file.filename);
});
// 업로드 된 파일을 정적컨텐츠로 유저에게 서비스 가능하게 함
app.use('/user', express.static('uploads'));
[뷰 파일 : /views_file/upload.ejs]
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h2><a href="">File upload with Multer</a></h2>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="userfile" />
<input type="submit" />
</form>
</body>
</html>
[POST로 전송한 파일의 세부정보]
{ fieldname: 'userfile',
originalname: 'dreampharos_logo.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'uploads/',
filename: 'eb297b785ee1f96391a43a9b668c7024',
path: 'uploads\\eb297b785ee1f96391a43a9b668c7024',
size: 42812 }
{ fieldname: 'userfile',
originalname: 'dreampharos_logo.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'uploads/',
filename: 'f818f546a999487a2a1296caf78e640e',
path: 'uploads\\f818f546a999487a2a1296caf78e640e',
size: 42812 }
[참고] 파일 업로드 (생활코딩)
[참조] 파일업로드3 - multer의 기본사용법 예제
댓글
댓글 쓰기