AngularJS Formdata文件数组上传

时间:2015-11-25 15:23:43

标签: java angularjs servlets form-data

我正在尝试一次性上传(实际上是POST)多个小文件以及一些键值对:

(((YourClass)value).getTime() > 60)

这是Java后端:

                $scope.uploadFiles = function(files) {

                    if (files.length === 0) {
                        return;
                    }

                    var formData = new FormData();
                    formData.append('keyName1', 'keyValue1');
                    formData.append('keyName2', 'keyValue2');
                    formData.append('keyName3', 'keyValue3');
                    for (var i = 0; i < files.length; i++) {
                        formData.append('files[]', files[i]);
                    }

                    $http.post( '/myEndpoint', formData, {
                        headers: { 'Content-Type': undefined },
                        transformRequest: angular.identity
                    }).success(function (result) {
                        console.log('YAY');
                    }).error(function () {
                        console.log('NAY');
                    });                 
                }

正在命中端点,但filesList长度为零。我也改变了

@RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
@ResponseBody
public void uploadFiles(
        @RequestParam("files") List<MultipartFile> fileList,
        @RequestParam("keyName1") String keyName1,
        @RequestParam("keyName2") String keyName2,
        @RequestParam("keyName3") String keyName3,
        HttpServletResponse response, HttpSession session) throws Exception {

    log.debug(fileList.size()); // Always logs zero
}

但这不起作用。

有人可以解决一些问题吗?

干杯,

2 个答案:

答案 0 :(得分:5)

这可能对您有所帮助。

Angular:

$scope.uploadFiles = function(files) {
    if (files.length === 0) {
        return;
    }

    var formData = new FormData();
    formData.append('keyName1', 'keyValue1');
    formData.append('keyName2', 'keyValue2');
    formData.append('keyName3', 'keyValue3');
    for (var i = 0; i < files.length; i++) {
        formData.append('file'+i, files[i]);
    }

    $http.post( '/myEndpoint', formData, {
        headers: { 'Content-Type': undefined },
        transformRequest: angular.identity
    }).success(function (result) {
        console.log('YAY');
    }).error(function () {
        console.log('NAY');
    });                 
}

On Spring / Java Side:

RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
public @ResponseBody Object uploadFiles(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
    //do stuff here...
    final String keyName1= request.getParameter('keyName1');
    //and so on......

    Iterator<String> iterator = request.getFileNames();
    MultipartFile multipartFile = null;
    while (iterator.hasNext()) {
        multipartFile = request.getFile(iterator.next());
        //do something with the file.....
    }
}

顺便说一下,在您有意义的一面,您可以随时结束文件或多次请求。它取决于您希望如何实现。

答案 1 :(得分:0)

我在GitHub上使用了一个库来帮助我使用Java Glassfish Server完成这项任务。

https://github.com/nervgh/angular-file-upload

我只需要上传一个文件,这里是接收该文件的Java后端。该框架确实支持将多个文件上传到服务器。

@POST
@Path("/Endpoint")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response whateverEndPoint(@FormDataParam("fileName") InputStream fileInputStream,
        @FormDataParam("fileName") FormDataContentDisposition contentDispositionHeader,
        @FormDataParam("additionalParameter") String additionalParameter) {

    System.out.println(contentDispositionHeader.getFileName());

    String output = "File Received on the server: ";

    return Response.status(200).entity(output).build();

}

这是我使用框架的角度控制器:

angular.module('AppThing').controller('DemoController',function($rootScope,$scope,FileUploader){

//creating the uploader with the correct url
$scope.uploader = new FileUploader({
    url : 'Endpoint',
    method : 'POST',
    alias: 'fileName',
    autoUpload:true
});

//runs right after we add a file to the queue
$scope.uploader.onAfterAddingFile = function(item){
};

//runs right before we upload an item to the server
$scope.uploader.onBeforeUploadItem = function(item){
        console.log('This is just before the image upload');
        item.formData.push({'additionalParameter':  $rootScope.additionalParameter});
};

$scope.uploader.onSuccessItem = function(item, response, status, headers) {

};



});

希望这有帮助