Download AngularJS Formdata Array File

I am trying to upload (actually POST) many small files in one row with several pairs of values:

                $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');
                    });                 
                }

Here's the Java backend:

@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
}

The endpoint is hit, but the length of the List file is zero. I also changed

    List<MultipartFile> fileList to MultipartFile[] filesArray

but it didn’t work.

Can anyone shed some light?

Greetings

Floor

+4
source share
2 answers

This may be useful for you.

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.....
    }
}

By the way, on the angular side, you can always finish the file in one go or with several requests. It is up to you how you want it to be implemented.

+5
source

GitHub, Java Glassfish.

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

, Java Backend . .

@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, :

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) {

};



});

,

0

Source: https://habr.com/ru/post/1617468/


All Articles