传递的base64字符串对象在AngularJS属性 [英] Passing base64 string to object's attribute in AngularJS

查看:759
本文介绍了传递的base64字符串对象在AngularJS属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过输入字段上传图片,领带的形象为Base64一个变量,那么这个变量添加到一个对象的属性,所以我可以将其存储在我的火力地堡分贝。

I'm trying to upload an image via an input field, tie the base64 of the image to a variable, then add that variable to the attribute of an object so I can store it in my Firebase db.

输入表单和放大器;为对象字段:

Input form & field for object:

      <div class="row modalDetail">
              <h3>New Episode</h3>
              <table class="">
                <tbody>
                  <tr>
                    <td class="labelField">Name</td>
                    <td><input type='text' ng-model='episode.name'></td>
                  </tr>
                  <tr>
                    <td class="labelField">Title</td>
                    <td><input type='text' ng-model='episode.title'></td>
                  </tr>
                  <tr>
                    <td class="labelField">Description</td>
                    <td><input type='text' ng-model='episode.shortDescription'></td>
                  </tr>
                  <tr>
                    <td class="labelField">Time</td>
                    <td><input type='text' ng-model='episode.time'></td>
                  </tr>
                </tbody>
              </table>
              <img src="../images/placeholder.png" id="pano">

              <!-- START Image File Upload -->        
                <td class="labelField">Image</td>
                <span class="btn btn-default btn-file">
                  <input type="file" accept="image/*" capture="camera" id="file-upload">
                </span>
                <div id="spin"></div>

              <div class='btn btn-warning' ng-click='createEpisode()'> Create an Episode</div>
      </div>

上传到火力地堡的服务:

The service for uploading to Firebase:

'use strict';

app.service('Uploader', ['$firebase', 'FIREBASE_TEST_URL', function($firebase, FIREBASE_TEST_URL) {

    var ref = new Firebase(FIREBASE_TEST_URL);

    var episodes = $firebase(ref);

    return {
        all: episodes,
        create: function(episode) {
            location.reload();
            //Add to firebase db
            return episodes.$add(episode);
        },
        delete: function(episodeId) { 
            location.reload();
            return episodes.$remove(episodeId);
        },
        update: function(episode) {
            location.reload();
            return episodes.$save(episode);
        }
    };
}]);

控制器具有文件处理的图像,等等:

Controller that has the file handling for the image, etc.:

'use strict';

app.controller('UploadCtrl', ['$scope', 'Uploader', function ($scope, Uploader) {

$scope.episodes = Uploader.all;

$scope.createEpisode = function(){
    Uploader.create($scope.episode).then(function(data){
        $scope.episode.name = '';
        $scope.episode.title = '';
        $scope.episode.description = '';
        $scope.episode.time = '';
        $scope.episode.img1 = $scope.episodeImgData;
    });
};

$scope.deleteEpisode = function(episodeId){
    bootbox.confirm('Are you sure you want to delete this episode?', function(result) {
        if (result === true) { 
            Uploader.delete(episodeId).then(function(data){
                console.log('Episode successfully deleted!');
            });
        }
    });
};

$scope.updateEpisode = function(episode) {
    Uploader.update($scope.episode).then(function(data) {
        console.log(episode);
        console.log('Episode successfully updated.');
    });
};

$scope.selectEpisode = function(object) {
    $scope.selectedEpisode = object;
    setTimeout(function(){ $scope.$apply($scope.selectedEpisode = object); });
};

// ********************************************************************************** //
// START Image Upload: https://github.com/firebase/firepano/blob/gh-pages/firepano.js //
// REQUIRED: app/scripts/js/crypto.js in index.js
var spinner = new Spinner({color: '#ddd'});
$scope.episodeImgData = '../images/defaultplaceholder.png';

function handleFileSelectAdd(evt) {
  var f = evt.target.files[0];
  var reader = new FileReader();
  reader.onload = (function(theFile) {
    return function(e) {
        var filePayload = e.target.result;
        var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));

        $scope.episodeImgData = e.target.result; 

        document.getElementById('pano').src = $scope.episodeImgData; 
        console.log($scope.episodeImgData);
    };
  })(f);
  reader.readAsDataURL(f);
}

function handleFileSelectEdit(evt) {
  var f = evt.target.files[0];
  var reader = new FileReader();
  reader.onload = (function(theFile) {
    return function(e) {
        var filePayload = e.target.result;
        var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));

        $scpope.episodeImgData = e.target.result; 

        document.getElementById('pano2').src = $scope.episodeImgData; 
        $scope.selectedEpisode.img1 = $scope.episodeImgData;
        console.log($scope.episodeImgData);
    };
  })(f);
  reader.readAsDataURL(f);
}

$(function() {
    $('#spin').append(spinner);
    document.getElementById('file-upload').addEventListener('change', handleFileSelectAdd, false);  
    document.getElementById('file-upload2').addEventListener('change', handleFileSelectEdit, false); 

});
// END Image Upload: https://github.com/firebase/firepano/blob/gh-pages/firepano.js //
// ******************************************************************************** //
}]);

在表单中的所有属性保存到数据库除IMG1。当点击更新按钮,我以为我可以在episodeImgData只传递对象(IMG1变量)来保存,但它不保存在所有的(只是表单变量绑episode.name等)的任何东西。什么是做到这一点的最好方法是什么?我使用的FirePano例子的部分( https://github.com /firebase/firepano/blob/gh-pages/firepano.js )为图像的处理。

All the attributes in the form save to the DB except img1. When the update button is clicked, I thought I could just pass in episodeImgData to the object (img1 variable) to save, but it doesn't save anything at all (just the form variables tied to episode.name, etc.). What's the best way to do this? I'm using parts of the FirePano example (https://github.com/firebase/firepano/blob/gh-pages/firepano.js) for the image handling.

推荐答案

有很多的小问题与code。

There were a lot of small problems with that code.


  • 由于您的发作是一个数组,你可以创建与 $ asArray ,否则将不会有一个 $添加方法:变种发作= $火力点(REF)$ asArray();

  • 您分别致电 location.reload()将数据发送到服务器之前

  • 您的文件上传处理程序不是触发我

  • 有来自firepano叼着引用微调

  • Since your episodes are an array, you can to create is with $asArray, otherwise it won't have a $add method: var episodes = $firebase(ref).$asArray();
  • You were calling location.reload() before sending the data to the server
  • Your file-upload handler wasn't triggering for me
  • There were dangling references to the spinner from firepano

我认为,前两次分别是最大的。但是,很难找到这种类型的问题,如果你不提供重现问题的小例子。我这样做,你现在。

I think that first two were the biggest. But it is hard to find that type of problem if you don't provide a minimal example that reproduces the problem. I did that for you now.

在最后,code不是太大,所以我会在这里分享:

In the end, the code is not too big so I'll share it here:

var app = angular.module('myapp', ['firebase'])
.service('Uploader', function($firebase) {
  var ref = new Firebase('http://<yourfirebase>.firebaseio.com/');
  var episodes = $firebase(ref).$asArray();
  return {
    all: episodes,
    create: function(episode) {
      //Add to firebase db
      return episodes.$add(episode);
    }
  };
})
.controller('UploadCtrl', function ($scope, Uploader) {
  $scope.episodes = Uploader.all;
  $scope.createEpisode = function() {
    if ($scope.episodeImgData) {
      $scope.episode.img1 = $scope.episodeImgData;
    }
    Uploader.create($scope.episode);
  };
  $scope.handleFileSelectAdd = function(evt) {
    var f = evt.target.files[0];
    var reader = new FileReader();
    reader.onload = (function(theFile) {
      return function(e) {
        var filePayload = e.target.result;
        $scope.episodeImgData = e.target.result; 
        document.getElementById('pano').src = $scope.episodeImgData; 
      };
    })(f);
    reader.readAsDataURL(f);
  };
  document.getElementById('file-upload').addEventListener('change', $scope.handleFileSelectAdd, false);
});

相应的(身体)HTML:

The corresponding (body) HTML:

<body ng-app='myapp'>
  <div class="row modalDetail" ng-controller='UploadCtrl'>
    <h3>New Episode</h3>
    <table class="" ng-model='episode'>
      <tbody>
        <tr>
          <td class="labelField">Name</td>
          <td><input type='text' ng-model='episode.name'></td>
        </tr>
        <tr>
          <td class="labelField">Title</td>
          <td><input type='text' ng-model='episode.title'></td>
        </tr>
        <tr>
          <td class="labelField">Description</td>
          <td><input type='text' ng-model='episode.shortDescription'></td>
        </tr>
        <tr>
          <td class="labelField">Time</td>
          <td><input type='text' ng-model='episode.time'></td>
        </tr>
      </tbody>
    </table>

    <td class="labelField">Image</td>
    <span class="btn btn-default btn-file">
      <input type="file" accept="image/*" capture="camera" id="file-upload">
    </span>
    <div class='btn btn-warning' ng-click='createEpisode()'>Create an Episode</div>
    <br/>
    <img id="pano">

  </div>
</body>

这是如果要创建具有可选的图像数据的插曲工作演示: http://jsbin.com/roriwu/ 7

This is a working demo if creating an episode with optional image data: http://jsbin.com/roriwu/7.

这篇关于传递的base64字符串对象在AngularJS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆