1. 程式人生 > >ionic本地相簿、拍照、裁剪、上傳(單圖完全版)

ionic本地相簿、拍照、裁剪、上傳(單圖完全版)

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 
      });
    }
  }
});