1 安装外部模块node-formidable
本模块的具体细节请参考https://github.com/felixge/node-formidable,它很好的抽象了解析上传文件的细节,使我们可以像处理post数据一样来处理上传的文件。
我们用nmp来安装formidable模块
C:\Users\xxx>npm install formidable
[email protected] node_modules\formidable
安装成功
2 改写server模块
var formidable = require('formidable'),http = require("http"),sys = require('sys');
function start(route, handle) {
function onRequest(request, response) {
if(request.url == '/upload' && request.method.toLowerCase() == 'post'){
var form = new formidable.IncomingForm();
form.parse(request,function(error,fields,files){
response.writeHead(200, {'content-type':'text/plain'});
response.write('receive upload:\n\n');
response.end(sys.inspect({fields: fields,files:files}));
});
return;
}
response.writeHead(200,{'content-type':'text/html'});
response.end(
'<form action="/upload" enctype="multipart/form-data" '+
'method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
3 上传文件后跳转到/upload页面显示结果
上传js文件
receive upload:
{ fields: { title: '2014 world cup' },
files:
{ upload:
{ domain: null,
_events: {},
_maxListeners: 10,
size: 301,
path: 'C:\\Users\\xxx\\AppData\\Local\\Temp\\53608004f2340d6b0697e387eeaf3a91',
name: 'index.js',
type: 'application/javascript',
hash: null,
lastModifiedDate: Wed Jun 25 2014 16:37:31 GMT+0800 (China Standard Time),
_writeStream: [Object] } } }
上传png图片
receive upload:
{ fields: { title: '2014 world cup' },
files:
{ upload:
{ domain: null,
_events: {},
_maxListeners: 10,
size: 429423,
path: 'C:\\Users\\xxx\\AppData\\Local\\Temp\\2a4c267e11f0c3c3bae6c7e552e3f79f',
name: 'chart1.png',
type: 'image/png',
hash: null,
lastModifiedDate: Wed Jun 25 2014 16:49:18 GMT+0800 (China Standard Time),
_writeStream: [Object] } } }