1.安装formidable
npm installformidable--save-dev //注意-g无效
2.在路由中引入
var formidable = require('formidable');
3.编写一个路由方法
router.post('/apply', function(req, res, next) {
res.locals.loginbean = req.session.loginbean;
var form = new formidable.IncomingForm();
form.encoding = 'utf-8';
form.uploadDir = './public/images/';
//---设置上传目录文件会自动保存在这里
form.keepExtensions = true;
//---保留后缀
form.maxFieldsSize = 5 * 1024 * 1024 ;
//---文件大小5M
form.parse(req, function (err, fields, files) {
if(err){
console.log(err);
}
let teacher= {};
//创建一个对象 为接收前端数据使用
teacher.role=2;
teacher.realname = fields.realname;
teacher.idnumber = fields.idnumber;
//fields为前端传过来的数据对象
teacher.photopath = (files.photo.path).replace('public\\','');
//files为前端传过来的文件数据对象
teacher.brief = fields.brief;
User.update({_id:res.locals.loginbean.id},{$set:teacher},function(err,rs){
if(err){
console.log(err);
res.send('数据库错误');
return;
}
req.session.loginbean.role=2;
res.send('alert("申请成功");location.href="//www.greatytc.com/home/";');
})
})