How to load an image that is already in <img src> in angularjs

I have an existing image that displays in <img ng-src=''>, and I want to upload (send along with my other json object) when I click the "Submit" button. The image exists, so I do not need to use <input type ="file">. But the code that I have does not work. Can anyone help me how to achieve this. Many thanks.

link plunker

+4
source share
1 answer

Some time has passed, however I just want to show how I implemented similar functionality

Demo

plnkr

Action plan :

  • img/URL Base64.
  • Base64 scope.

:

  • factory URL- Base64 canvas promises.
  • fileInput , load img Base64 imgData scope.
  • imgData, Base64 formData

link: function(scope, ele, attrs) {
  ele.bind('load', function(e) {
    var imgSrc = e.target.src;
    urlToBase64.getData(imgSrc).then(function(data) {
      scope.imgData = data;
    });
    scope.$apply();
  });
}

Factory

myApp.factory('urlToBase64', ['$q', function($q) {

  var obj = {};
  // function to convert URL to Base64 representation
  function URLtoBase64(url, callback) {
    var defer = $q.defer();

    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function() {
      var canvas = document.createElement('CANVAS');
      var ctx = canvas.getContext('2d');
      canvas.height = this.height;
      canvas.width = this.width;
      ctx.drawImage(this, 0, 0);
      try {
        defer.resolve(canvas.toDataURL());
      } catch (e) {
        defer.reject(e);
      }
      canvas = null;
    };
    img.src = url;

    return defer.promise;
  }

  obj.getData = URLtoBase64;
  return obj;
}]);

var fd = new FormData();
// imgData is coming from fileInput directive
fd.append('file', $scope.imgData);
fd.append('formdata', JSON.stringify($scope.dataform));
var reqObject = {
  url: 'admin/managecuisineAdd',
  method: 'POST',
  data: fd,
  transformRequest: angular.identity,
  headers: {
    'Content-type': undefined
  }
};
$http(reqObject).then(function(data) {
  $scope.status = data;
  $scope.itemlist.push(data)
  $scope.message = "New Dish Added Successfully"
});
0

Source: https://habr.com/ru/post/1617188/


All Articles