Passing base64 string to object's attribute in AngularJS

后端 未结 1 1992
醉话见心
醉话见心 2020-12-10 00:02

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 Fi

1条回答
  •  难免孤独
    2020-12-10 00:45

    Update (20160519): Firebase just released a new feature called Firebase Storage. This allows you to upload images and other non-JSON data to a dedicated storage service. We highly recommend that you use this for storing images, instead of storing them as base64 encoded data in the JSON database.

    There were a lot of small problems with that code.

    • 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.

    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://.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);
    });
    

    The corresponding (body) HTML:

    
      

    New Episode

    Name
    Title
    Description
    Time
    Image
    Create an Episode

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

    0 讨论(0)
提交回复
热议问题