【问题标题】:Ionic Photo Upload - File to Base64 String离子照片上传 - 文件到 Base64 字符串
【发布时间】:2017-05-15 09:59:40
【问题描述】:

我正在开发一个与 Rails API 通信的 Ionic 应用程序。我有用户,用户有图片。我已经能够关注this guide,了解如何让用户从他们的手机图像中本地抓取图像。

这允许用户从他们的手机中抓取图像

$ionicPlatform.ready(function() {
 $scope.getImageSaveContact = function() {
 // Image picker will load images according to these settings
  var options = {
    maximumImagesCount: 1,
    width: 800,
    height: 800,
    quality: 80
  };

  $cordovaImagePicker.getPictures(options).then(function (results) {
    // Loop through acquired images
    for (var i = 0; i < results.length; i++) {
      $scope.collection.selectedImage = results[i];   // We loading only one image so we can use it like this

      window.plugins.Base64.encodeFile($scope.collection.selectedImage, function(base64){  // Encode URI to Base64 needed for contacts plugin
        $scope.collection.selectedImage = base64;
      });
    }
    console.log("results");
    console.log(results);
  }, function(error) {
    console.log('Error: ' + JSON.stringify(error));
  });
 };
});

问题是,它没有运行(或似乎没有运行)编码文件的window.plugins.Base64.encodeFile 行。现在,它只是图像文件,而不是 Base64 编码的字符串。

从我的设备摄像头抓取文件后,如何运行此功能?

我想通了,答案在下面

【问题讨论】:

    标签: angularjs ionic-framework


    【解决方案1】:

    来自一个旧项目https://github.com/aaronksaunders/firebaseStorageApp/blob/master/www/js/app.js#L132

      return $cordovaFile.readAsArrayBuffer(path, fileName)
        .then(function (success) {
          // success - get blob data
          var imageBlob = new Blob([success], { type: "image/jpeg" });
       })
    

    【讨论】:

    • 感谢您的回答。我几乎所有代码都保持不变,但用你的替换了我的$cordovaImagePicker.getPictures(在我的编辑中)。我添加了一系列警报(在ionic view 上进行测试)并收到文件名完成的警报。但是,它不会进入第二个then 块。您认为有什么理由会出现这种情况吗?
    • 你安装了cordova-file插件吗?
    • 是的,我做到了。 this is the one I installed
    【解决方案2】:

    添加这个相机插件

    cordova plugin add cordova-plugin-camera
    

    默认返回base 64的图片..

    $scope.choosePhoto = function () {
                $scope.myPopup.close();
                var options = {
                    quality: 75,
                    destinationType: Camera.DestinationType.DATA_URL,
                    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                    allowEdit: true,
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 300,
                    targetHeight: 300,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false
                };
                $cordovaCamera.getPicture(options).then(function (imageData) {
                    $scope.imgURI = "data:image/jpeg;base64," + imageData;
    
                }, function (err) {
                    // An error occured. Show a message to the user
                });
            }
    

    更多细节可以在这里找到 http://ngcordova.com/docs/plugins/camera/

    希望这会有所帮助...

    【讨论】:

      【解决方案3】:

      我能够通过拼凑一堆东西来解决这个问题,尤其是在导轨一侧。这个想法是单击一个按钮来获取图像,从相机胶卷中选择一张,将该图像转换为 base64 字符串,然后将该图像发送到服务器。

      我当前的堆栈是 rails 4,ionic/angular v1。希望这对其他人有帮助。

      角度控制器

      function toDataUrl(url, callback) {
          var xhr = new XMLHttpRequest();
          xhr.onload = function() {
            var reader = new FileReader();
            reader.onloadend = function() {
              callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
          };
          xhr.open('GET', url);
          xhr.responseType = 'blob';
          xhr.send();
        }
      
        $scope.grabImage = function () {
          var options = {
            maximumImagesCount: 1,
            width: 800,
            height: 800,
            quality: 80
          };
      
          $cordovaImagePicker.getPictures(options).then(function (results) {
            $scope.dataImg = results;
      
            return toDataUrl($scope.dataImg, function(base64Img) {
              $scope.base64 = base64Img;
              $state.go($state.current, {}, {reload: false});
            })
          }, function(error) {
            $scope.message = "Error: Failed to Attach Image";
      
            var alertPopup = $ionicPopup.alert({
              title: 'User Photos',
              templateUrl: 'templates/modals/success_or_error.html',
              scope: $scope
            });
          });
        }
      

      导轨控制器

        def create
          image = Paperclip.io_adapters.for(params[:image_file])
          image.class.class_eval { attr_accessor :original_filename, :content_type }
          image.original_filename = "mu_#{@current_mobile_user.id}_#{@current_mobile_user.pictures.count}.jpg"
          image.content_type = "image/jpeg"
          @picture = @current_mobile_user.pictures.create(image: image, imageable_id: @current_mobile_user.id)
      
          if @picture.save
            render json: ['Picture Uploaded!'], status: :created
          else
            render json: [@picture.errors.full_messages.to_sentence], status: :unprocessable_entity
          end
        end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-19
        相关资源
        最近更新 更多