0

I am trying to upload image into the folder with angularjsand php.

Here is html part:

<button ng-click="addNewEvent()">Add Event</button>
<form ng-submit="addRoadmapEvent(events)">
  <span ng-repeat="event in events">
    <input type="text" ng-model="event.month" required=""/>
    <input type="file" ng-model="event.img" file-input="files" />
  </span>
  <input type="submit" value="Submit">
</form>

Function addNewEvent() allows to add another row with month and image so I will have something like this:

enter image description here

Then after pressing submit button I want to move selected images into my folder, I am using directive for it and then addRoadmapEvent function:

$scope.addRoadmapEvent = function (events){
  var imgs = [];
  var form_data = new FormData();
  //set the data array
  angular.forEach(events, function(event){
    imgs.push(event.img);
  });

  var i = 0;
  angular.forEach(imgs, function(file){
    console.log(i++);
    form_data.append('file', file[0]);
    $http.post('House/house_action.php/roadmap_img', form_data, {transformRequest: angular.identity,headers: {'Content-Type': undefined,'Process-Data': false}}).then(function(response){  
      console.log(response.data);
    });
  }); 
};

It works perfectly the only problem is $http.post. Its posting same photo twice:

enter image description here

How can i make it send one by one?

1 Answer 1

2

Move the FormData constructor inside the loop:

$scope.addRoadmapEvent = function (events){
  var imgs = [];
  ̶v̶a̶r̶ ̶f̶o̶r̶m̶_̶d̶a̶t̶a̶ ̶=̶ ̶n̶e̶w̶ ̶F̶o̶r̶m̶D̶a̶t̶a̶(̶)̶;̶
  //set the data array
  angular.forEach(events, function(event){
    imgs.push(event.img);
  });

  var i = 0;
  angular.forEach(imgs, function(file){
    console.log(i++);
    //INSIDE the loop
    var form_data = new FormData();
    form_data.append('file', file[0]);
    $http.post('House/house_action.php/roadmap_img', form_data, {
         transformRequest: angular.identity,
         headers: {
            'Content-Type': undefined,
            'Process-Data': false
         }
    }).then(function(response){  
      console.log(response.data);
    });
  }); 
};
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.