🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
文件上传需要以下multiparty: 因为涉及修改文件名,所以还需要fs组件 npm install multiparty --save npm install fs --save 页面reg.html: ~~~ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="../javascripts/jquery-3.2.0.min.js"></script> <script> $(function(){ $("#btn_reg").click(function(){ var formdata = new FormData(document.getElementById("myform")); $.ajax({ url:"../users/reg", type:"post", data:formdata, contentType:false, processData:false, success:function(data) { console.log(data); } }); }); }) </script> </head> <body> <form id="myform" method="post" enctype="multipart/form-data"> <div> <div id="photos"> <div id="addfile"> <img src="img/addfile.jpg"/> <input name="photo" type="file" accept="image/*" /> </div> </div> </div> <div class="form-div"> 姓名:<input class="form-control" type="text" name="name" /> </div> <div class="form-div"> 密码:<input class="form-control" type="text" name="pwd" /> </div> <div class="form-div"> 性别:<input type="radio" name="sex" value="女" checked /> 女 <input type="radio" name="sex" value="男" /> 男 </div> <div class="form-div"> 生日:<input class="form-control" type="date" name="birthday" /> </div> <div class="form-div"> 薪水:<input class="form-control" type="text" name="sal" /> </div> <button id="btn_reg" type="button">注册</button> </form> </body> </html> ~~~ user.js ~~~ var multiparty = require('multiparty'); var fs = require('fs'); router.post('/reg', function(req, res, next) { //文件上传位置 var form = new multiparty.Form({uploadDir: './public/files'}); //上传完成后处理 form.parse(req, function(err, fields, files) { var name = fields.name[0]; var pwd = fields.pwd[0]; var sex = fields.sex[0]; var birthday = fields.birthday[0]; var sal = fields.sal[0]; var photo = files.photo[0].originalFilename; //改文件名 fs.rename(files.photo[0].path,'./public/files/'+files.photo[0].originalFilename, function(err){ console.log(err); }) var obj = {name:name,pwd:pwd,birthday:new Date(birthday),sal:sal,photo:photo}; var userdao = new UserDAO(); userdao.addUser(obj,function(){ res.send("注册成功"); },function(){ res.send("注册失败"); }); }); }); ~~~