在restangular中为单个请求设置标头和http参数

时间:2014-01-22 19:23:06

标签: angularjs post file-upload restangular

我正在尝试使用restangular来处理文件上传请求,我希望在restangular中实现与下面相同的功能。 但是,我不确定如何为此特定请求设置内容类型和transformRequest。如果我理解正确,setDefaultHeader会为所有后续请求设置它。还有其他方法吗?

myApp.service('$fileUpload', ['$http', function ($http) {
   this.uploadFileToUrl = function(file, uploadUrl){
      var filedata = new FormData();
      filedata.append('file', file);
      $http.post(uploadUrl, filedata, {
         transformRequest: angular.identity,
         headers: {'Content-Type': undefined}
      })
      .success(function(){
      })
      .error(function(){
      });
     }
}]);

3 个答案:

答案 0 :(得分:8)

这里有2种情况,POST用于创建新项目或PUT用于编辑项目:

// Save new Item
$scope.saveNew = function (item) {

  var data = new FormData();
  angular.forEach(item, function (fieldData, field) {
    data.append(field, fieldData);
  });

  Restangular
    .all('items')
    .withHttpConfig({transformRequest: angular.identity})
    .post(data, {}, {'Content-Type': undefined})
    .then(function () {
      // do on success
    }, function () {
      // do on failure
    });
};

// Edit existing Item
$scope.save = function (item) {

  var data = new FormData();
  angular.forEach(item.plain(), function (fieldData, field) {
    data.append(field, fieldData);
  });

  Restangular
    .one('items', item._id)
    .withHttpConfig({transformRequest: angular.identity})
    .customPUT(data, undefined, {}, {'Content-Type': undefined})
    .then(function () {
      $location.path('sites');
    });

答案 1 :(得分:6)

要设置单个请求的标头,您需要做的就是添加一个包含标头名称和值的对象作为.post(),. get()或您需要的任何方法的参数

https://github.com/mgonto/restangular#element-methods

Restangular.all('some-endpoint').post(postContent, {}, {'Content-Type': undefined}).then(function (response) {
    console.log('Weeeeee!!!');
});

至于我不确定的transformRequest,我以前不必处理过类似的事情,这是我在文档中唯一能找到的东西:

https://github.com/mgonto/restangular#setdefaulthttpfields

但这似乎是针对所有要求设定的,这不是你想要的,但它至少是一些东西。

无论如何,希望这会帮助你得到你想要的东西。

修改

由于restangular中的大多数请求类型都有一个查询参数,然后你需要传递一个空白的查询param对象然后是标题,所以示例已经更新以显示这一点。

答案 2 :(得分:5)

由于这是此问题首次出现在Google上,请参阅Restangular问题跟踪器中的Issue 420

基本上,最新的Restangular在调度请求之前有一个withHttpConfig函数来设置$http选项。

如果您的网址类似于example.com/api/users/:id/picture的网址接受带有特定用户图片的分段上传,您可以执行以下操作:

Users.one(2)
    .withHttpConfig({transformRequest: angular.identity})
    .customPOST(filedata, 'picture', undefined, {'Content-Type': undefined})
    .then(function(resp) {
        // File data post is complete here
    });

默认情况下,Angular会将使用$http发送的任何数据转换为JSON。 transformRequest配置只是用NOP替换默认转换。