详解ionic本地相册、拍照、裁剪、上传(单图完全版)
网络上已有的ionic图片选择上传博客碎片化过于严重,功能残缺或者引入了一些不必要的插件。这次以项目为契机,把ionic的图片选择、裁剪、上传整合一下,多图上传请戳ionic选择多张图片上传
插件安装
cordovapluginaddcordova-plugin-camera//用于通过相机、相册选择图片并完成裁剪 cordovapluginaddcordova-plugin-file-transfer//用于上传图片到服务器
将功能封装为服务
angular.module('starter.services',[]) //文件上传 .factory('UploadFile',function(Toast){ return{ /** *上传文件到服务器 * *@paramfileUrl文件路径 *@paramserver服务器接口 */ uploadFile:function(fileUrl,server){ document.addEventListener("deviceready",onDeviceReady,false); functiononDeviceReady(){ varoptions=newFileUploadOptions(); options.fileKey="BeanYon"; options.fileName=fileUrl.substr(fileUrl.lastIndexOf('/')+1); options.mimeType="image/jpeg"; options.chunkedMode=false; varparams={account:localStorage.account}; options.params=params; varft=newFileTransfer(); ft.upload(fileUrl, encodeURI(server), success, err, options); } functionsuccess(r){ Toast.show("设置头像成功"); } functionerr(error){ Toast.show("上传头像失败,请确保网络正常后再试"); } } } }) //配置单张图片选择 .factory('SelectPicture',function(UploadFile,Toast){ return{ /** *从相机或图库选择一张图片 * *@paramtype选择类型,0拍照,1相册 *@paramwidth目标宽度 *@paramheight目标高度 *@paramscope$scope对象 */ chooseSinglePicture:function(type,width,height,scope){ document.addEventListener("deviceready",onDeviceReady,false); functiononDeviceReady(){ varoptions={//相机配置 targetWidth:width, targetHeight:height, quality:100, allowEdit:true } if(type==1){//图片源设置为相册 options.sourceType=2; } navigator.camera.getPicture( function(res){ scope.avatar_src=res; scope.$apply(); localStorage.avatar=res; UploadFile.uploadFile(res,"我的服务器地址");//传递自己的服务器接口地址 },function(res){ Toast.show("选择头像失败"); },options ); } }, /** *从图库选择多张图片 */ choosePictures:function(){ window.imagePicker.getPictures(function(res){ alert(res+",success"); },function(res){ alert(res+",failed"); },{ maximumImagesCount:10, width:80, height:80, quality:80 }); } } });
调用服务
angular.module('starter.controllers',[]) .controller('MyCtrl',function($scope,$state,$ionicActionSheet,UploadFile,Toast,SelectPicture){ $scope.avatar_src="img/default_avatar.jpg"; /** *选择头像 */ $scope.selectAvatar=function(){ //显示操作表 $ionicActionSheet.show({ buttons:[ {text:'拍照 '}, {text:'
从相册选择 '}, ], buttonClicked:function(index){ //设置头像 SelectPicture.chooseSinglePicture(index,120,120,$scope); returntrue; } }); } })
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。