最近一个项目中,用到了MUI上传用户头像,官方这部分文档我没有找到,于是从网上扒拉出来别人的开始踩坑,以下是已经成功的代码,可自行参考。
首先添加一个头像的li
<li class="mui-table-view-cell infoName" id="userImg"> <a class="mui-navigate-right" href="#">头像</a> <img class="mui-badge userImg" src="../../images/head_default.png" id="headimg"/> </li>
点击之后要弹出拍照及从相册选项的菜单:
document.getElementById('userImg').addEventListener('tap',function(){ if(mui.os.plus){ var a=[{ title:'拍照' },{ title:'从手机相册选择' }]; plus.nativeUI.actionSheet({ title:'修改头像', cancel:'取消', buttons:a },function(b){ switch(b.index){ case 0: break; case 1: //拍照 getImages(); break; case 2: //打开相册 galleryImages(); break; default: break; } },false); } });
对应的拍照函数为:
//拍照 function getImages(){ var mobileCamera=plus.camera.getCamera(); mobileCamera.captureImage(function(e){ plus.io.resolveLocalFileSystemURL(e,function(entry){ var path=entry.toLocalURL()+'?version='+new Date().getTime(); uploadHeadImg(path,uid); },function(err){ console.log("读取拍照文件错误"); }); },function(e){ console.log("er",err); },function(){ filename:'_doc/head.png'; }); }
从相册选择的函数为:
//从本地相册选择 function galleryImages(){ plus.gallery.pick(function(a){ plus.io.resolveLocalFileSystemURL(a,function(entry){ plus.io.resolveLocalFileSystemURL('_doc/',function(root){ root.getFile('head.png',{},function(file){ //文件已经存在 file.remove(function(){ entry.copyTo(root,'head.png',function(e){ var path=e.fullPath+'?version='+new Date().getTime(); uploadHeadImg(path,uid); },function(err){ console.log("copy image fail: ",err); }); },function(err){ console.log("删除图片失败:("+JSON.stringify(err)+")"); }); },function(err){ //打开文件失败 entry.copyTo(root,'head.png',function(e){ var path=e.fullPath+'?version='+new Date().getTime(); uploadHeadImg(path,uid); },function(err){ console.log("上传图片失败:("+JSON.stringify(err)+")"); }); }); },function(e){ console.log("读取文件夹失败:("+JSON.stringify(err)+")"); }); }); },function(err){ console.log("读取拍照文件失败: ",err); },{ filter:'image' }); };
这是将图片转为base64的函数:
//将图片压缩转成base64 function getBase64Image(img) { var canvas = document.createElement("canvas"); var width = img.width; var height = img.height; if (width > height) { if (width > 100) { height = Math.round(height *= 100 / width); width = 100; } } else { if (height > 100) { width = Math.round(width *= 100 / height); height = 100; } } canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, width, height); /*绘图*/ var dataURL = canvas.toDataURL("image/png", 0.8); return dataURL.replace("data:image/png;base64,", ""); }
图片上传到服务器函数为:
function uploadHeadImg(imgPath,uid) { var images = new Image(); images.src = imgPath; images.onload = function() { var imgData = getBase64Image(images); mui.ajax('你的图片上传接口', { data: { 'imgData':imgData }, dataType: 'json', type: 'post', timeout: 10000, success: function(data) { if(data.code == 200){ var headimg = document.getElementById('headimg'); if(headimg){ headimg.src = data.data; } } mui.toast(data.msg) }, error: function(xhr, type, errorThrown) { endLoad(); mui.alert('网络或接口异常,请检查网络或稍后重试!'); } }); } }
我的后端接口使用的TP,因此使用的函数是:
//UPLOAD_PATH:请先自己定义 public function uploadheadimg() { if (request()->isPost()) { $uid = trim(input('param.uid/d')); $imgData = input('param.imgData'); $this->checkuid($uid); $imageName = date("YmdHis",time())."_".rand(1111,9999).'.png'; $Path = UPLOAD_PATH.'headimg/'; $Pathwithfile = $Path.$imageName; if (!is_dir($Path)){ mkdir($Path,0777,true); } $r = file_put_contents($Pathwithfile, base64_decode($imgData)); if (!$r) { return json(['code'=>-1,"data"=>'',"msg"=>"头像上传失败"]); }else{ $do_Path = substr($Pathwithfile,strlen(ROOT_PATH)); //$do_Path即为图片路径,然后加上自己的域名,输出就可以了 return json(['code'=>200,'data'=>$do_Path,'msg'=>'上传成功']); } } }