2014-10-27 55 views
0

根据主题行我希望上传/发送文件到服务器使用AngularJS和春天。 当我从客户端提交文件时,它包含$scope.file = "fileURL.jpg",但在服务器上收到file = null,并且控制台返回:data = {"description":"Test","status":"REJECTED"}。 下面是我的代码:如何发送文件到服务器使用AngularJS和春天

我的看法:

<label class="control-label col-sm-4 col-xs-12" for="file">Please upload the file : <span class="required">*</span> </label> 
<div class="col-xs-4 input-max controls "> 
    <input class="inline-block" type="file" name="file" ng-model="file" data-rule-required="true" id="file" accept=".jpg, .jpeg"> 
</div> 

和AngularJs控制器:

var test = { 
     description:"Test", 
     status: "REJECTED" 
    }; 

var fd = new FormData(); 
fd.append('data', angular.toJson(test)); 
fd.append("file", $scope.file); 
$http({ 
    method: 'POST', 
    url: 'EmployeeService/employee/data/fileupload', 
    headers: {'Content-Type': undefined}, 
    data: fd, 
    transformRequest: angular.identity 
}) 
.success(function(data, status) { 
       alert("success"); 
}); 

春控制器:

@ResponseBody 
@RequestMapping(value = "/data/fileupload", method = RequestMethod.POST) 
public String postFile(@RequestParam(value="file", required=false) MultipartFile file, 
         @RequestParam(value="data") Object data) throws Exception { 
    System.out.println("data = " + data); 
    return "OK!"; 
} 

回答

1

在HTML:

<input type="file" ng-file-select="onFileSelect($files)" multiple accept="image/*"> 

在JavaScript的:

$scope.onFileSelect = function($files) { 
    for (var i = 0; i < $files.length; i++) { 
     var file = $files[i]; 
    var test = { 
     description:"Test", 
     status: "REJECTED" 
     }; 
    var fd = new FormData(); 
    fd.append('data', angular.toJson(test)); 
    fd.append("file", file); 
    $http({ 
     method: 'POST', 
     url: 'EmployeeService/employee/data/fileupload', 
     headers: {'Content-Type': undefined}, 
     data: fd, 
     transformRequest: angular.identity 
     }) 
     .success(function(data, status) { 
      alert("success"); 
     }); 
    } 
} 

在服务器:

@ResponseBody 
@RequestMapping(value = "/data/fileupload", method = RequestMethod.POST) 
public String postFile(@RequestParam(value="file", required=false) MultipartFile file, 
         @RequestParam(value="data") Object data) throws Exception { 
    System.out.println("data = " + data); 
    return "OK!"; 
} 
+0

我想用地图<字符串,对象>而不是对象的数据。这怎么可能? – 2015-11-06 05:20:14

相关问题