如何使用AngularJS和Spring将文件发送到服务器

时间:2014-10-27 11:45:55

标签: angularjs spring

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

我有看法:

<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");
});

Spring控制器:

@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 个答案:

答案 0 :(得分: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!";
}