2013-10-25 30 views
1

我使用angularjs在单个请求中将文件和json对象上传到nodejs服务器。然后我在萤火虫上得到这个console.log:将文件附加到FormData不能在angularjs中工作

-----------------------------8791641017658 Content-Disposition: form-data; name="model" {"phone":"asasasa","description":"121212112","payment":"2121212121","shipping":"121221221","imageurl":"21212112","price":"212112212","status":"new"} -----------------------------8791641017658-- 

因此,名称=“文件”不会出现在这里。

而在服务器的NodeJS的执行console.log(req.files)// print out "{}"

请帮帮忙,谢谢!

$scope.files = []; 

     $scope.$on("fileSelected", function (event, args) { 

     $scope.$apply(function() {    
      //add the file object to the scope's files collection 
      $scope.files.push(args.file); 
      console.log($scope.files); 

     }); 
     }); 

    $scope.create = function() { 
     $scope.seller_submit = { 
      phone: this.phone, 
      description: this.description, 
      payment: this.payment, 
      shipping: this.shipping, 
      imageurl: this.imageurl, 
      price: this.price, 
      status: this.status 
     }; 

     $http({ 
      method: 'POST', 
      url: '/articles/'+ $routeParams.articleId, 

      headers: { 'Content-Type': undefined }, 

      transformRequest: function (data) { 
       var formData = new FormData(); 

       formData.append("model", angular.toJson(data.model)); 

       for (var i = 0; i < data.files; i++) { 

        formData.append("file" + i, data.files[i]); 
       } 
       return formData; 
      }, 

      data: { model: $scope.seller_submit, files: $scope.files } 

     }). 
     success(function (data, status, headers, config) { 
      alert("success!"); 
     }). 
     error(function (data, status, headers, config) { 
      alert("failed!"); 
     }); 

回答

3

您可以创建为

myApp.service('uploadsService', function($http) { 

    var code = ''; 
    var fileName = ''; 


    this.uploadFile = function(files) { 


     var fd = new FormData(); 

     //Take the first selected file 
     fd.append("image", files[0]); 

     var promise = $http.post('/uploads/uploadFile.json', fd, { 
       withCredentials: true, 
       headers: {'Content-Type': undefined }, 
       transformRequest: angular.identity 
      }).then(function(response) { 

      code = response.data.code; 
      fileName = response.data.fileName; 

      return{ 
       code: function() { 
        return code; 
       }, 
       fileName: function() { 
        return fileName; 
       } 
      }; 
     }); 
     return promise; 
    }; 

    }); 

所以,你可以在你的控制器服务做这样的事情:

$scope.uploadFile = function(files) { 

        uploadsService.uploadFile(files).then(function(promise){ 

         $scope.code = promise.code(); 
         $scope.fileName = promise.fileName(); 
    }); 

    }; 

而在你的看法:

<input type="file" onchange="angular.element(this).scope().uploadFile(this.files)" ng-model="image"> 

适用于我:)

+0

工程就像一个魅力。 – JayPea

+0

这只适用于上传一个文件吗? – nam