如何将数据对象和文件图像从angularJs发送到nodeJS

时间:2017-03-25 14:38:39

标签: html angularjs node.js jax-rs

我正在寻找如何从从angularJS发送到nodeJS的表单(文本字段和图像)中检索信息。

-Html代码:

<form role="form" enctype="multipart/form-data" name="myForm">
<input type="text"  ng-model="UserName" required="required">
<input type="text"  ng-model="FirstName" required="required">
<input type="file"  ng-model="Image" required="required">
<button type="submit" ng-click="addUser()">save</button>
</form>
  • Angular.js文件:
$scope.addUser=function(){
      var user ={
            UserName: $scope.UserName,
           FirstName:$scope.FirstName
                  };
                console.log("info User: "+user.UserName);//Well recovered data

              $http.get(url+"/add",$scope.user,$scope.Image)
              .success(function(data){
                      $scope.ListUsers=data;
              }).error(function(err,data){
                  console.log("error " +err);
              }); 
           };
  • Node.js文件:
    app.get("/add",function (req,res) {  console.log("data of user: "+req.body); //undefined
 http.get(url+"/AddRest",req.body,req.Image, function (repsHttp) {
 //error here
                         var body='';
                          repsHttp.on('data',function(d) {
                              body += d;
                          });
                          repsHttp.on('end',function() {
                              try {
                                  var user = JSON.parse(body);
                              } catch(e) {
                                  console.log('error ', +body);
                              }
                              res.json(user);
                          });
                      });
                  });

-API JAX-RS添加用户:

@RequestMapping(value="/add",headers = "content-type=multipart/*")
    @Consumes("multipart/form-data")
    public Users AddUser( @FormDataParam("file") InputStream uploadedInputStream,
            @RequestParam(value="file") MultipartFile fileDetail, 
            HttpServletRequest request,
            @RequestBody(required=false) Users user){

            UM.AddDataUsers(uploadedInputStream,fileDetail,user);
                        }
谢谢你的帮助,

1 个答案:

答案 0 :(得分:0)

首先要做的事情.Angular的ng-model对type=“file”的输入不起作用所以我们需要创建自己的指令来将文件绑定到视图控制器中的变量。

.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

相应范围内的变量。这是使用$ parse服务在我们的范围中设置值来实现的。视图中指令所需的标记很简单

<input type="file" file-model="Image" required>

当您向服务器发送图像时,需要以multipart/form-data格式发送图像。由于你需要发送带有图像的json,你需要附加json对象formData并发送它。它也应该是post请求。无法使用获取请求发送数据

$scope.addUser = function() {
    $scope.user = {
        UserName: $scope.UserName,
        FirstName: $scope.FirstName
    };
    var fd = new FormData();
    angular.forEach($scope.Image, function(file) {
        fd.append('file', file);
    });
    fd.append('user', JSON.stringify($scope.user));
    $http.post(url + "/add", fd, {
            transformRequest: angular.identity,
            headers: {
                'Content-type': undefined
            }
        })
        .success(function(data) {
            $scope.ListUsers = data;
        }).error(function(err, data) {
            console.log("error " + err);
        });
}

同时将节点方法更改为发布

app.post("/add", function(req, res) {
    console.log("data of user: " + req.body);
})