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/';
//---設(shè)置上傳目錄文件會自動保存在這里
form.keepExtensions = true;
//---保留后綴
form.maxFieldsSize = 5 * 1024 * 1024 ;
//---文件大小5M
form.parse(req, function (err, fields, files) {
if(err){
console.log(err);
}
let teacher= {};
//創(chuàng)建一個對象 為接收前端數(shù)據(jù)使用
teacher.role=2;
teacher.realname = fields.realname;
teacher.idnumber = fields.idnumber;
//fields為前端傳過來的數(shù)據(jù)對象
teacher.photopath = (files.photo.path).replace('public\\','');
//files為前端傳過來的文件數(shù)據(jù)對象
teacher.brief = fields.brief;
User.update({_id:res.locals.loginbean.id},{$set:teacher},function(err,rs){
if(err){
console.log(err);
res.send('數(shù)據(jù)庫錯誤');
return;
}
req.session.loginbean.role=2;
res.send('alert("申請成功");location.href="/home/";');
})
})