安装formidable
pm install [email protected]
客户端表单提交
<form class= "Form-signin" role= "form" method= "post" enctype= ' Multipart/form-data ' >
Server-side specified routing rulesRouter.post ('/upload ',function(req, res) {varform =NewFormidable. Incomingform ();//Create an upload formform.encoding = ' utf-8 ';//Set EditForm.uploaddir = ' public ' + avatar_upload_folder;//Set upload directoryForm.keepextensions =true;//reserved suffixForm.maxfieldssize = 2 * 1024 * 1024;//File SizeForm.parse (req,function(Err, fields, files) {if(Err) {Res.locals.error=err; Res.render (' Index ', {title: ' title ' }); return; } console.log (fields); varExtname = ";//suffix name Switch(files.fulAvatar.type) { Case' Image/pjpeg ': Extname= ' jpg '; Break; Case' Image/jpeg ': Extname= ' jpg '; Break; Case' Image/png ': Extname= ' png '; Break; Case' Image/x-png ': Extname= ' png '; Break; } if(Extname.length = = 0) {Res.locals.error= ' support only PNG and JPG images '; Res.render (' Index ', {title:title}); return; } varAvatarname = math.random () + '. ' +Extname; varNewPath = Form.uploaddir +Avatarname; Console.log (NewPath); Fs.renamesync (Files.fulAvatar.path, NewPath); }); Res.render (' Upload ', {title: ' Upload Demo ' }); });
View Codenode. js form Upload