标签:
web 项目应用express4.0框架
html 表单post 文件上传失败,后端无法获取提交文件
express不支持文件上传。
方式一
若是图片,可以将图片转码为BASE64上传
前端框架angularjs代码 转换代码如下
$scope.filechange=function(index){ var file = this.files[0]; var url = webkitURL.createObjectURL(file); /* 生成图片 * ---------------------- */ var $img = new Image(); $img.src = url; $img.onload = function () { //生成比例 var width = this.width, height = this.height, scale = width / height; width = parseInt(800); height = parseInt(width / scale); //生成canvas var $canvas = $(‘#canvas‘); var ctx = $canvas[0].getContext(‘2d‘); $canvas.attr({ width: width, height: height }); ctx.drawImage($img, 0, 0, width, height); var base64 = $canvas[0].toDataURL(‘image/jpeg‘, 0.5); var cc = $("#pic" + index); cc.attr("src", url); postdata["file" + index] = base64.substr(23); } } $scope.upload=function(){ $http.post(‘UploadFile/FenXiangImg?wxopenid=222&orderid=111&templateid=1‘,$scope.postdata).success(function(data) { alert("sucess"); }); }
方式二
nodejs 后端引用connect-multiparty包
后端代码如下
路由
var multipart = require(‘connect-multiparty‘); var multipartMiddleware = multipart(); app.post(‘/q/people/insertPeoples‘, multipartMiddleware, function(req, res) { if(req.session&&req.session.account) { var filepath=req.files.peoples.path; console.log(req); People.insertPeoples(req,res,filepath); } else{ res.send({error:1}) } });
业务逻辑实现
function insertPeoples(req,res,filepath) { basemodule.checkAccountRole(req,res,function(account) { fs.readFile(filepath, function (err, filedata) { console.log(err +filedata); csv.parse(filedata, {comment: ‘#‘}, function(err, output){ fs.unlink(filepath, function (err) { }); var allpeoples=[]; var keys=[‘_id‘,‘idcard‘,‘wechatuid‘,‘qqnum‘,‘mac‘,‘name‘]; console.log(JSON.stringify(output)); output.forEach(function(people){ var peopleobj={}; for(var i =0;i<keys.length;i++){ peopleobj[keys[i]]=people[i]; } if(peopleobj.mac){ peopleobj.mac=peopleobj.mac.toUpperCase(); } allpeoples.push(peopleobj); }); if(allpeoples.length>0){ db.insertPeoples(allpeoples,account,function(err,doc){ if(!err){ res.redirect(‘/#people‘); }else{res.send({error:1})} }) } else{ res.redirect(‘/#people‘); } }); }); }) }
标签:
原文地址:http://www.cnblogs.com/zihunqingxin/p/4435774.html