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

Asked

Viewed 2,344 times

3

I want to send an image (I will save it in bank), but I do not know how to send it together on 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();
    });
};
  • 1

    http://stackoverflow.com/q/6150289/4190610

  • Tell me something, the moment the user chooses an image, user.imageProfile has what value?

  • @jbueno it doesn’t even show the attribute in the user object

2 answers

1


I decided by converting the image to Base64, used angular-Base64-upload, was 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();
    });
};

Showing:

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

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 about the function Formdata.

The ideal would be to save the image in base 64, so it occupies less space in the database, but there are other ways to save the image, being able to send them to a Web Service, treat them and then save them in a file server, among other things. See if this solves for you, if not, take a look at Angular’s own plugins to upload, for example Ng-File-Upload or Flowjs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.