Ionic V1表单上传照片(相机或文件)

时间:2017-08-21 18:30:21

标签: cordova ionic-framework

我在离线v1上的stackoverflow(和其他网站)上一直在搜索,但找不到我的问题的好答案。

我的申请要求用户定期填写带有他的照片或照片集的表格。

在一个常规的角度应用程序中,我使用带有multipart / formdata +输入类型=文件的表单但是每次我搜索时都会离子,我得到相同的anwser:使用$ cordovaCamera,$ cordovaFile,$ cordovaFileTransfer,$ cordovaDevice等等。

问题是,我更愿意使用表单中的文件和数据向服务器发送一个唯一的请求。

有没有人暗示我该如何完成它?

2 个答案:

答案 0 :(得分:0)

您是否想过,获取图像然后将其转换为base64格式?

查看cordova相机github页面(Link), 将输出图像作为base64非常简单。

function cameraCallback(imageData) {
   var image = document.getElementById('myImage');
   image.src = "data:image/jpeg;base64," + imageData;
}

然后,使用图片中的base64字符串,您可以将表单数据和图像数据一起发送到服务器。

答案 1 :(得分:0)

我希望这会对你有所帮助 的的index.html

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *"/>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="js/ng-cordova.min.js"></script>
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
  </head>
  <body ng-app="starter">
  <ion-content class="has-header padding" ng-controller="ImageController">
    <button class="button button-full button-energized" ng-click="addMedia()">
      Add image
    </button>
    <button class="button button-full button-positive" ng-click="sendEmail()">
      Send mail
    </button>
    <br><br>
    <ion-scroll direction="y" style="height:200px; min-height: 200px; overflow: scroll; white-space: nowrap;">
      <img ng-repeat="image in images track by $index" ng-src="data:image/jpeg;base64,{{image}}" style="height:200px; padding: 5px 5px 5px 5px;"/>
    </ion-scroll>

  </ion-content>
</body>
</html>

<强> controller.js

 angular.module('starter')

.controller('ImageController', function($scope, $cordovaDevice, $cordovaFile, $ionicPlatform, $cordovaEmailComposer, $ionicActionSheet, ImageService, FileService) {

  $ionicPlatform.ready(function() {
    $scope.images = FileService.images();
    $scope.$apply();
  });

  $scope.addMedia = function() {
    $scope.hideSheet = $ionicActionSheet.show({
      buttons: [
        { text: 'Take photo' },
        { text: 'Photo from library' }, 
          {  text: '<b ng-disabled="user.length<1">Delete</b>',
              type: 'input type="file"'}
      ],
      titleText: 'Add images',
      cancelText: 'Cancel',
      buttonClicked: function(index) {
        $scope.addImage(index);
      }
    });
  }

  $scope.addImage = function(type) {
    $scope.hideSheet();
    ImageService.handleMediaDialog(type).then(function() {
      $scope.$apply();
    });
  }

  $scope.sendEmail = function() {
    if ($scope.images != null && $scope.images.length > 0) {
      var mailImages = [];
      var savedImages = $scope.images;
      for (var i = 0; i < savedImages.length; i++) {
          mailImages.push('base64:attachment'+i+'.jpg//' + savedImages[i]);
        }
      $scope.openMailComposer(mailImages);
    }
  }

  $scope.openMailComposer = function(attachments) {
    var bodyText = '<html><h2>My Images</h2></html>';
    var email = {
        to: '',
        attachments: attachments,
        subject: 'Devdactic Images',
        body: bodyText,
        isHtml: true
      };

    $cordovaEmailComposer.open(email, function(){
        console.log('email view dismissed');                                                      
    }, this);
  }
});

<强> service.js

 angular.module('starter')

.factory('FileService', function() {
  var images;
  var IMAGE_STORAGE_KEY = 'dav-images';

  function getImages() {
    var img = window.localStorage.getItem(IMAGE_STORAGE_KEY);
    if (img) {
      images = JSON.parse(img);
    } else {
      images = [];
    }
    return images;
  };

  function addImage(img) {
    images.push(img);
    window.localStorage.setItem(IMAGE_STORAGE_KEY, JSON.stringify(images));
  };

  return {
    storeImage: addImage,
    images: getImages
  }
})

.factory('ImageService', function($cordovaCamera, FileService, $q, $cordovaFile) {

  function optionsForType(type) {
    var source;
    switch (type) {
      case 0:
        source = Camera.PictureSourceType.CAMERA;
        break;
      case 1:
        source = Camera.PictureSourceType.PHOTOLIBRARY;
        break;
    }
    return {
      quality: 90,
      destinationType: Camera.DestinationType.DATA_URL,
      sourceType: source,
      allowEdit: false,
      encodingType: Camera.EncodingType.JPEG,
      popoverOptions: CameraPopoverOptions,
      saveToPhotoAlbum: false,
      correctOrientation:true
    };
  }

  function saveMedia(type) {
    return $q(function(resolve, reject) {
      var options = optionsForType(type);

      $cordovaCamera.getPicture(options).then(function(imageBase64) {        
            FileService.storeImage(imageBase64);      
      });
    })
  }
  return {
    handleMediaDialog: saveMedia
  }
});