(1)设置from表单属性:标签内设置属性enctype=”multipart/form-data”,方式为post。
<form action="/api/user/register" method="post" enctype="multipart/form-data"> <div class="title"><span>注册</span></div> <div class="line"><span class="colDark">用户名:</span><input name="username" type="text"></div> <div class="line"><span class="colDark">密码:</span><input name="password" type="password"></div> <div class="line"><span class="colDark">确认:</span><input name="repassword" type="password"></div> <div class="line"><span class="colDark">头像:</span><input name="img" type="file" required></div> <div class="line"><span class="colDark"></span><button type="submit">注 册</button></div> <p class="texyRight">已有账号?<a href="javascript:;" class="colMint">马上登录</a> </p> </form>
(2)nodejs使用npm命令安装 下载multer模块(我是全局安装的)
npm install --save multer -g
(3)在项目js文件引入:
var bodyParser =require('body-parser'); app.use(bodyParser.urlencoded({extended:true})); var fs = require('fs'); var multer = require('multer'); var upload = multer({ dest: 'uploads/' });//设置上传文件的路径 /* 用户注册:1、用户名不能为空;2、密码不能为空;3、两次密码输入必须一致 */ router.post('/api/user/register', upload.any(), function (req, res, next) { console.log(req.files); // 上传的文件信息 var username = req.body.username;//用户名 var password = req.body.password;//密码 var repassword = req.body.repassword;//二次密码 var oname = req.files[0].originalname;//文件名 var path1 = req.files[0].path;//原上传文件 // 设置转移路径,以及重命名(最后存放照片的目录) var image_path = './public/img/image/' + oname; // 将上传后的文件移动到指定路径目录下 fs.rename(path1, image_path, (err) => { console.log(err); }); })