使用angular.forEach函数

时间:2019-05-13 07:38:52

标签: angularjs asynchronous post

我正在尝试使用angularjsphp将图像上传到文件夹中。

这是html部分:

<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>

函数addNewEvent()允许添加带有月份和图像的另一行,因此我将具有以下内容:

enter image description here

然后,在按下提交按钮之后,我要将选定的图像移动到我的文件夹中,我正在为其使用指令,然后使用addRoadmapEvent函数:

$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);
    });
  }); 
};

它完美运行,唯一的问题是$http.post。其两次发布同一张照片:

enter image description here

我如何使其一一发送?

1 个答案:

答案 0 :(得分:2)

在循环内移动FormData构造函数:

$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);
    });
  }); 
};