前jQuery端接收数据
function upAvatar(img){
console.log(img); // data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMD…/7vA+eq/xZAlzs/wBYlP8AtlpRRXcc9h++B/8AVyJRs30UVRkM2e9M8s+tFFSBE6UUUUGp/9k=
$.ajax({
url:'/user/upload',
type:'PUT',
data:{
imgData: img
},
success: function (){
botbox.alert('上传成功!');
},
error: function (){
bootbox.alert('上传失败,请稍后再试!');
}
});
}
Nodejs(express)后端接收数据
app.put('/user/upload',function(req,res){
if(req.body.imgData){
var avatar = req.body.imgData.replace(/^data:image\/\w+;base64,/, '');
var fs = require('fs'),
newBuff = new Buffer(avatar, 'base64');
fs.writeFile('./public/img/' + req.session.token + '.jpg', newBuff, 'binary', function (err) {
if (err){
return res.sendStatus(500);
}
res.sendStatus(200);
});
}else{
res.sendStatus(400);
}
});