Node.js + Express + MongoDB 基础篇 #6 上传文件

资源

代码

varexpress=require('express');varbodyParser=require('body-parser');varfs=require('fs');varapp=express();varmulter=require('multer');varcreateFolder=function(folder){try{fs.accessSync(folder);}catch(e){fs.mkdirSync(folder);}};varuploadFolder='./upload/';createFolder(uploadFolder);varstorage=multer.diskStorage({destination:function(req,file,cb){cb(null,uploadFolder);},filename:function(req,file,cb){cb(null,file.originalname);}});varupload=multer({storage:storage});// create application/json parservarjsonParser=bodyParser.json()// create application/x-www-form-urlencoded parservarurlencodedParser=bodyParser.urlencoded({extended:false})app.get('/',function(req,res){console.dir(req.query);res.send("home page: "+req.query.find);});app.get('/form',function(req,res){varform=fs.readFileSync('./form.html',{encoding:"utf8"});res.send(form);});app.post('/',urlencodedParser,function(req,res){console.dir(req.body);res.send(req.body.name);});app.post('/upload',upload.single('logo'),function(req,res){console.dir(req.file);res.send({'ret_code':0});});app.get('/profile/:id/user/:name',function(req,res){console.dir(req.params);res.send("You requested to see a profile with the name of "+req.params.name);});app.get('/ab?cd',function(req,res){res.send('/ab?cd');})app.listen(3000);console.log('listening to port 3000');