Is there any way to send image by JSON to an api?

3

I want to send an image (I'll save it to the same bank), but I do not know how to send it together in POST .

I'm using AngularJs :

<input type="file" ng-model="user.imageProfile">
$scope.register = function (user) {

    if (user.password != user.passwordConfirm) {
        $rootScope.showToast("Confirmação de senha inválida!");
        return null;
    }

    $http.post($rootScope.serviceBase + "users", user).then(function () {
        $rootScope.showToast("Cadastrado com sucesso");
        $mdDialog.cancel();
    });
};
    
asked by anonymous 04.11.2016 / 11:58

2 answers

1

I decided to convert the image to Base64 , I used angular-base64-upload , like this:

Input:

<input type="file" ng-model="image" base-sixty-four-input>

Controller:

$scope.register = function (user) {
    if (user.password != user.passwordConfirm) {
        $rootScope.showToast("Confirmação de senha inválida!");
        return null;
    }

    $scope.user.imageProfile = $scope.image.base64;

    $http.post($rootScope.serviceBase + "users", user).then(function () {
        $rootScope.showToast("Cadastrado com sucesso");
        $mdDialog.cancel();
    });
};

Display:

<img data-ng-src="data:image/png;base64,{{ userAuthenticated.imageProfile }}" title="{{ userAuthenticated.name }}" class="photoUser" data-err-src="images/png/avatar.png"/>
    
04.11.2016 / 13:09
0

Try using the FormData function.

var formData = new FormData();
formData.append("file", $scope.file);

$http({
  method: 'POST',
  url: $rootScope.serviceBase + "users", user,
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  data: {
    file: formData
  }
}).
then(function(result) {
  console.log(result);
  return result.data;
});

Support for this function is only in new browsers. Can I Use? .

More information on the FormData function.

Ideally, you save the base64 image, so it takes up less of your database space, but there are other ways you can save the image to a Web Service, treat it, and then save it to a server of files, among other things. See if that solves for you, if not, take a look at Angular's own plugins to upload, such as Ng- File-Upload or FlowJS .

    
04.11.2016 / 12:28