【问题标题】:Ionic V1 form upload with photo ( camera or file )Ionic V1 表单上传照片(相机或文件)
【发布时间】:2018-01-29 21:48:38
【问题描述】:

我在 ionic v1 上的 stackoverflow(和其他网站)上进行了很多搜索,但找不到适合我的问题的好答案。

我的应用程序要求用户定期用他的图片或图片集填写表单。

在常规的 Angular 应用程序中,我会使用带有 multipart/formdata + 输入类型 = 文件的表单,但在 ionic 上,每次搜索时,我都会得到相同的答案:使用 $cordovaCamera、$cordovaFile、$cordovaFileTransfer、$cordovaDevice 等等.

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

有没有人提示我如何完成它?

【问题讨论】:

    标签: cordova ionic-framework


    【解决方案1】:

    你有没有想过,获取图片,然后转换成base64格式?

    看cordova相机github页面(Link), 将输出图像获取为 base64 相当简单。

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

    然后,使用图像中的 base64 字符串,您可以将普通的 http POST 请求连同表单数据和图像数据一起发送到服务器。

    【讨论】:

      【解决方案2】:

      希望对你有帮助 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
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-24
        • 2017-03-07
        • 2018-11-18
        • 1970-01-01
        • 2021-07-08
        • 2019-11-12
        • 1970-01-01
        相关资源
        最近更新 更多