欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解ionic本地相册、拍照、裁剪、上传(单图完全版)

程序员文章站 2022-03-07 16:59:13
网络上已有的ionic图片选择上传博客碎片化过于严重,功能残缺或者引入了一些不必要的插件。这次以项目为契机,把ionic的图片选择、裁剪、上传整合一下,多图上传请戳...

网络上已有的ionic图片选择上传博客碎片化过于严重,功能残缺或者引入了一些不必要的插件。这次以项目为契机,把ionic的图片选择、裁剪、上传整合一下,多图上传请戳

插件安装

cordova plugin add cordova-plugin-camera //用于通过相机、相册选择图片并完成裁剪
cordova plugin add cordova-plugin-file-transfer //用于上传图片到服务器

将功能封装为服务

angular.module('starter.services', [])

//文件上传
.factory('uploadfile', function(toast) {
 return {
 /**
  * 上传文件到服务器
  *
  * @param fileurl 文件路径
  * @param server 服务器接口
  */
 uploadfile: function(fileurl, server) {
  document.addeventlistener("deviceready", ondeviceready, false);
  function ondeviceready() {
  var options = new fileuploadoptions();
  options.filekey = "beanyon";
  options.filename = fileurl.substr(fileurl.lastindexof('/') + 1);
  options.mimetype = "image/jpeg";
  options.chunkedmode = false;

  var params = {account: localstorage.account};
  options.params = params;

  var ft = new filetransfer();
  ft.upload(fileurl, 
     encodeuri(server), 
     success, 
     err, 
     options);
  }

  function success(r){
  toast.show("设置头像成功");
  }

  function err(error){
  toast.show("上传头像失败,请确保网络正常后再试");
  }
 }
 }
})

//配置单张图片选择
.factory('selectpicture', function(uploadfile, toast) {
 return {
 /**
  * 从相机或图库选择一张图片
  * 
  * @param type 选择类型,0 拍照,1 相册
  * @param width 目标宽度
  * @param height 目标高度
  * @param scope $scope对象
  */
 choosesinglepicture: function(type, width, height, scope) {
  document.addeventlistener("deviceready", ondeviceready, false);
  function ondeviceready() {
  var options = {//相机配置
   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: '<p style="font-size: 18px;">拍照<p>' },
  { text: '<p style="font-size: 18px;">从相册选择<p>' },
  ],
  buttonclicked: function(index) {
  //设置头像
  selectpicture.choosesinglepicture(index, 120, 120, $scope);
  return true;
  }
 });
 }
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。