使用Angular JS在同一请求中上载文件Formdata和JSON数据

时间:2015-08-03 07:43:40

标签: jquery angularjs http-headers form-data

如何将我的两个$ http.post合并到单个http帖子中?

$scope.myMethod = function(){
    var fd = new FormData();
    angular.forEach($scope.files, function(file){
        fd.append('file', file);
    });

    $http.post('my_url', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).success(function(result){
        console.log(result);
    });

    $http.post('my_url', {imgx: $scope.imgx, imgy: $scope.imgy, imgh: $scope.imgh, imgw: $scope.imgw}).success(
        function(data){
        console.log(data);
    });
}

非常感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:1)

try something like this:

$scope.myMethod = function(){
    var fd = new FormData();
    angular.forEach($scope.files, function(file){
        fd.append('file', file);
    });

var data = {};
    data.fd = fd;
    data.otherData  =   {imgx: $scope.imgx, imgy: $scope.imgy, imgh: $scope.imgh, imgw: $scope.imgw};  

    $http.post('my_url', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).success(function(result){
        console.log(result);
    });


}

答案 1 :(得分:0)

没有合并它们你就可以听到这样的2个承诺:

var promise1 = $http.post('my_url', fd, { .....

var promise2 = $http.post('my_url', {imgx: $scope.imgx, ......

$q.all([promise1,promise2]).then(function(response){ console.log(response); });

angular $ q documentation