2014.4월 현재 나와있는 예제들은 express가 버전업되면서 모두 제대로 동작 하지않습니다.
formidable 플러그인을 이용한 방법이 있습니다.
https://github.com/felixge/node-formidable
자세한 내용은 위의 주소에서 확인할수 있습니다.
대략내용은 파일업로드를 위하여 만든 플러그인이라고 합니다.
참고자료 :
http://helloraspberrypi.blogspot.kr/2014/04/upload-file-using-nodejs-with-formidable.html
-소스-
/*
<!-- index.html 파일예 --->
<form method="post" enctype="multipart/form-data" action="http://localhost:8081/file-upload">
<input type="file" name="thumbnail">
<input type="submit">
</form>
*/
var theApp = {
version : '0.2',
module_path : '',
port : 8081
};
//command line argument parse
process.argv.forEach(function(val, index, array) {
//console.log(index + ': ' + val);
if(val.indexOf('=') > 0) {
var tokens = val.split('=');
switch (tokens[0]) {
case 'port':
theApp.port = parseInt(tokens[1]);
break;
case 'module_path':
theApp.module_path = tokens[1];
break;
}
}
});
//console.log(theApp);
// run the command to install formidable
// $ npm install formidable
var formidable = require( theApp.module_path +'formidable');
var http = require('http');
var util = require('util');
var fs = require('fs');
var os = require('os');
var UrlParser = require('url');
var app = http.createServer(
function(req, res){
switch(req.method){
case 'GET':
process_get(req, res);
break;
case 'POST':
process_post(req, res);
break;
}
}
);
app.listen(theApp.port);
console.log('tiny upload server v ' + theApp.version );
console.log(' start port : '+ theApp.port + ', ready ok!');
//Display my IP
(function get_MyIP() {
var networkInterfaces = os.networkInterfaces();
for (var interface in networkInterfaces) {
networkInterfaces[interface].forEach(
function(details){
if (details.family=='IPv4'
&& details.internal==false) {
console.log(interface, details.address);
}
});
}
})();
//get 처리 해주기
function process_get(req, res){
var result = UrlParser.parse(req.url,true);
switch (result.pathname) {
case '/test':
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
break;
default :
break;
}
}
function process_post(req, res){
var form = new formidable.IncomingForm();
form.uploadDir = "./uploads"; //업로드할위치 지정
form.keepExtensions = true; //확장자 이름 써주기
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
var resultObj = {
result : 'ok',
size : files.thumbnail.size,
path : files.thumbnail.path,
name : files.thumbnail.name,
type : files.thumbnail.type
}
res.end( JSON.stringify(resultObj));
//res.end('File uploaded!');
console.log(files.thumbnail.path + "Upload completed" );
//console.log(util.inspect(files));
//console.log(files.thumbnail.name);
});
}
'server' 카테고리의 다른 글
우분투에 오라클 클라이언트 인터페이스 설치하기(OCI) (0) | 2014.03.08 |
---|