Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert image to base64 in angularjs

I have a requirement where user will upload their image and i have to convert it into something and send it to .Net REStful service. I am new to angular js. Could someone please help

like image 240
user2610160 Avatar asked Nov 13 '14 09:11

user2610160


1 Answers

You can use the angular custom directive to convert the image base64. directive.js

myApp.directive('imgUpload', ['$rootScope',function (rootScope) {
  return {
    restrict: 'A',
    link: function (scope, elem, attrs) {
      var canvas = document.createElement("canvas");
      var extensions = 'jpeg ,jpg, png, gif';
      elem.on('change', function () {
      reader.readAsDataURL(elem[0].files[0]);
      var filename = elem[0].files[0].name;

        var extensionlist = filename.split('.');
        var extension =extensionlist[extensionlist.length - 1];
            if(extensions.indexOf(extension) == -1){
                alert("File extension , Only 'jpeg', 'jpg', 'png', 'gif', 'bmp' are allowed.");       

            }else{
                    scope.file = elem[0].files[0];
                    scope.imageName = filename;
                }
      });

            var reader = new FileReader();
            reader.onload = function (e) {

              scope.image = e.target.result;
              scope.$apply();

            }
        }
    }
}]);

Html:

<div class="input-group">
  <input id="image" class="hidden" type="file" img-upload ng-model="imageName" name="imageName">
  <img ng-src="{{image}}" height="100" width="100" ng-show="image"/>
  <label for="image" class="btn btn-success btn-xs pull-center" name="upload" Value="">Upload Photo</label>
</div>

Now you need to add your code in controller which works for storing image or file in database.

like image 51
Bipin Shilpakar Avatar answered Nov 02 '22 06:11

Bipin Shilpakar