byCoder
byCoder

Reputation: 9184

angularJS make binary data image from base64 and send as image file to server

I'm using this tool to crop images in my AngularJS app: https://github.com/fengyuanchen/cropper

and then I try to store data to server, but now I send base64 code... How could I send normal cropped image binary code, not as base64? is it real?

my code for uploading is such:

var addImage = function(files) {
      var deferred = $q.defer();
      var fd = new FormData();      

      var blob = new Blob([files], { type : "image/png"});
      fd.append("file", blob);

      $http.post(settings.apiBaseUri + "/files", fd, {
          withCredentials: true,
          headers: {
            'Content-Type': undefined
          },
          transformRequest: angular.identity
        })
        .success(function(data, status, headers, config) {
          url = data.Url;
          deferred.resolve(url);
        })
        .error(function(err, status) {

        });
      return deferred.promise;
    };

and here I send base64 code:

  $scope.photoChanged = function(files) {
    $scope.oldImg = angular.element(document.querySelector('#avatar-id'));
    $scope.files = files;        
    var reader = new FileReader();
    reader.onload = function(e) {
      $scope.imagecontent = e.target.result;
    };
    reader.readAsDataURL(files[0]);
  };

and

  $scope.setCroppedData = function(data) {
    $('#avatar-id').attr('src', data);
    $scope.nImg = new Image();
    $scope.nImg.src = data;  // data - is base64 image code
  }
  ...
  uploaderService.addImage($scope.nImg.src).then(function(url) {
    $scope.person.AvatarUrl = url;
    $scope.updateContactQuery();
  });
  ...

how could I send like I do without any croping: send image file, so that i could go via link in browser and see image, but not a byte64 code???

Upvotes: 2

Views: 8600

Answers (1)

Rebornix
Rebornix

Reputation: 5270

You can wrap the base64 data in ArrayBuffer then convert to binary Image data like:

var binaryImg = atob(base64Image);
var length = binaryImg.length;
var arrayBuffer = new ArrayBuffer(length);
var uintArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < length; i++) {
    uintArray[i] = binaryImg.charCodeAt(i);
}

I suppose uintArray is what you want.

Upvotes: 2

Related Questions