由于公司自主研发APP,使用的是MUI框架。我做了其中头像图片上传的功能,在此分享下demo;
如有不规范处,请多多指教,互相学习。
第一次接触这个框架,踩了许多的坑 >_<
步骤:点击选择图片 → 图片转BASE64发送到服务器 → 服务器解码写入流中,返回地址
1.选择图片
2.后台服务器解码
3.上传完成
D:\ tu
展示前端代码
头像<img src="" id="userPhoto" onclick="choosePhoto(this)"/></a><script src="js/jquery.min.js" charset="utf-8"></script>
<script src="js/mui.min.js" charset="utf-8"></script>
<script type="text/javascript">mui.init(); function choosePhoto(event) {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(event);break;case 2://打开相册 galleryImages(event);break;default:break;}}, false);}}//拍照 function getImages(event) {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, event);console.log(path);}, function(err) {console.log("读取拍照文件错误");});}, function(e) {console.log("er", err);}, function() {filename: '_doc/head.png';});}//本地相册选择 function galleryImages(event) {console.log("你选择了从相册选择");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() {console.log("文件移除成功");entry.copyTo(root, 'head.png', function(e) {var path = e.fullPath + '?version=' + new Date().getTime();uploadHeadImg(path, event);}, 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, event);}, function(err) {console.log("上传图片失败:(" + JSON.stringify(err) + ")");});});}, function(e) {console.log("读取文件夹失败:(" + JSON.stringify(err) + ")");});});}, function(err) {console.log("读取拍照文件失败: ", err);}, {filter: 'image'});};//上传图片function uploadHeadImg(imgPath, event) {var hint=document.getElementById('hint');hint.style.display="inline-block";hint.innerHTML='上传中...';hint.style.color="#778899";//选中图片之后,头像当前的照片变为选择的照片var mainImg = event;mainImg.src = imgPath;var image = new Image();image.src = imgPath;image.onload = function() {var path='/api/appUser/uploadCheckPhoto';var picNum=event.id;var base64 = getBase64Image(image);var jsonObj = {'token':stateText,'picNum':picNum,}var url = getApiUrl(path,jsonObj);mui.ajax(url,{data:{'imgDatas':base64},dataType: 'json', //服务器返回json格式数据type: 'post', //HTTP请求类型timeout: 25000, //超时时间设置为25秒;success: function(data) {if (data.code == 0) {localStorage.setItem('$head_image',data.src);simulateLoading(container,0,100);setTimeout(function() {//mui.toast(data.msg);hint.innerHTML='上传成功';hint.style.color="#3CB371";},2560);}else{mui.alert(data.msg);}},error: function(xhr, type, errorThrown) {if (type == 'timeout') {mui.alert('服务器连接超时,请稍后再试');}}});}}//压缩图片转成base64function getBase64Image(img) {var w = 200imgWidth = img.width;imgHeight = img.height;var canvas = document.createElement("canvas");var ctx = canvas.getContext("2d");if (Math.max(imgWidth, imgHeight) > w) {if (imgWidth > imgHeight) {canvas.width = w;canvas.height = w * imgHeight / imgWidth;} else {canvas.height = w;canvas.width = w * imgWidth / imgHeight;}} else {canvas.width = imgWidth;canvas.height = imgHeight;}ctx.clearRect(0, 0, canvas.width, canvas.height);ctx.drawImage(img, 0, 0, canvas.width, canvas.height);var dataUrl = canvas.toDataURL("image/png", 0.8);return dataUrl;}
展示后台代码
@PostMapping("/uploadPhoto")@ResponseBodypublic R upload(String imgDatas,String id,String picNum) {String imgDatas= json.getString("userid");String id= json.getString("id");String picNum = json.getString("imgDatas");String src=null;try {src=ImgBase64Decoder.photo(imgDatas, id, picNum);} catch (Exception e) {}return src;}
图片解密工具类:
/*** Base64解码为图片写入流* @param imgDatas* @param id* @param picNum* @return*/public static String photo( String imgDatas,String id,String picNum) {String bs = "data:image/png;base64,";String base = imgDatas.replace(bs, "");BASE64Decoder decoder = new BASE64Decoder();String imgFilePath=null;try {//解码byte[] b = decoder.decodeBuffer(base);for (int i = 0; i < b.length; ++i) {//调整异常数据if (b[i] < 0) {b[i] += 256;}}imgFilePath = "D:\\tu\\" + id+ "_" + picNum + ".png";OutputStream out = new FileOutputStream(imgFilePath);out.write(b);out.flush();out.close();} catch (Exception e) {return "error";}return imgFilePath;}
源码地址:https://download.csdn.net/download/weixin_38407595/11834171
学习视频链接:https://blog.csdn.net/weixin_38407595/article/details/102561868