0

I have a problem sending data via POST in angular, my data include 2 files and some text field, the problem is that the service doesn't receives any data.

this is my code:

var inputs = document.querySelectorAll( 'input[type="file"]' );

Array.prototype.forEach.call( inputs, function( input ){
    input.addEventListener( 'change', function( e ){
    if(this.id == "zipToUpload")
            $scope.zipToUpload = this.files[0];
        else
            $scope.imgToUpload = this.files[1];
    });
}); 

$scope.submit = function(){
    var getInput = {nome: $scope.app_name, zipToUpload: $scope.zipToUpload, imgToUpload: $scope.imgToUpload, url: $scope.app_url,
        secure: $scope.checkbox_pass, hide: $scope.checkbox_hide, beta: $scope.checkbox_beta, password: $scope.app_pass, location: "1" };

    var req = {
        method: 'POST',
        url: 'api/rest/app/insert_app.php',
        headers: {
            'Content-Type': undefined
        },
        data: getInput
    }

    $http(req)
    .then(function(result) {
            console.log(result);        
    });
}
1
  • When the AngularJS $http service gets a JavaScript object to POST, it serializes the object into a JSON text string. Files are exotic host-based objects that can not be serialized. That is why the server is not receiving the files. There are WebAPI that can work with exotic File objects. It is necessary to know what formats the server can accept to answer the question of how to send them. Commented Mar 31, 2017 at 16:30

1 Answer 1

1

You can not directly upload file using model in angular. First you need a directive to bind files to the model.

   myApp.directive('fileModel', ['$parse', function ($parse) {
        return {
           restrict: 'A',
           link: function(scope, element, attrs) {
              var model = $parse(attrs.fileModel);
              var modelSetter = model.assign;

              element.bind('change', function(){
                 scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                 });
              });
           }
        };
     }]);

And the input will be like :

 <input type = "file" file-model = "myFile"/>

And the you can send post request using form data

$scope.upload = funtion(){
  var fd = new FormData();
  fd.append('file', $scope.myFile);
  var req = {
    method: 'POST',
    url: 'api/rest/app/insert_app.php',
    headers: {
        'Content-Type': undefined
    },
    data: fd
   }

$http(req)
.then(function(result) {
        console.log(result);        
});
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.