用nodejs处理文件上传(1)

1 安装外部模块node-formidable
本模块的具体细节请参考https://github.com/felixge/node-formidable,它很好的抽象了解析上传文件的细节,使我们可以像处理post数据一样来处理上传的文件。
我们用nmp来安装formidable模块
C:\Users\xxx>npm install formidable
formidable@1.0.15 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] } } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值