http获取和发布Angular

时间:2017-01-07 12:16:43

标签: javascript angularjs http post

你好,我的json"名字" :

[
    {
        "file": "file1.zip",
        "date": "12-03-2016",
    },
    {
        "file": "file2.zip",
        "date": "24-06-2016",
    },
    {
        "file": "file3.zip",
        "date": "02-12-2016",
    }]

我的javascript文件:

var app = angular.module('app', []);
    app.service('service', function($http, $q){
        var deferred = $q.defer();

        $http.get('newapi.json').then(function(data){
            deferred.resolve(data);
        });

        this.getNames = function(){
            return deferred.promise;
        }
    });
    app.controller('FirstCtrl', function($scope, service){
        var promise = service.getNames();
        promise.then(function(data){
            $scope.names = data.data;
            $scope.namesplit = $scope.names;
            $scope.namesplit.map(function(item) {
                item.time = new Date(item.date * 1000);
            });
            console.log($scope.namesplit);
        });
        });

和HTML:

<tr ng-repeat="name in names">
   <td>{{name.file}}</td>
   <td>{{name.date}}</td>
   <td><button>POST</button></td>
</tr>

我有一张桌子,当我点击按钮时,我需要的是&#34;文件&#34;邮寄到服务员。我知道我必须使用$ http.post,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

太简单了 Html

<button ng-click="post()">Click Me</button>

控制器

    $scope.post=function(){
$http.post(URL HERE, data-here, {    
 })
  .then(function onSuccess(response) {
    // Handle success
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  }).
  catch(function onError(response) {
    // Handle error
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  });
  }

答案 1 :(得分:0)

要使用$http.post()功能上传文件,您必须设置一些其他参数,例如headerstransformRequest

这是一个简单的例子:

$scope.postToServer = function(){
    var fd = new FormData();
    fd.append('file', file); 
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
}

注意:在此示例中,文件var是位于客户端文件系统上的文件的内容,uploadUrl是处理请求的服务的URL。