1

I am using ng-file-upload to select multiple files.But my requirement is that i want to attach those selected files as a file list into my Js object and send this object to server through REST.So far my data inserting part is working fine with out file list.

REST Service Code Snippet

@POST
@Path("/manual")
@Produces(MediaType.APPLICATION_JSON)
public boolean insertResults(testVO testResult) {

    for(Object o:testVO.getFiles()){

       //File access code goes here    
    }
}

testVO.Java class

private String fName;
private String lName;
private Object[] files;
... getter and setter methods goes here

JsFiddle HTML form

Sample

Angular Js code snippet for insert form data

$scope.insertResults= function(tc){
var result = {};
result.lName= tc.lName;
result.fName= tc.fName;
result.files=$scope.files; //This also works but i can not access file content
Service.ManualResult.insertResults({},result)
.$promise.then(function(data){
//succes code goes here
},function(error) {
//error 
}
};

my requirement is that how can i send list of files along with the form data and access each uploaded files details in server side.

Note: when i call testVO.getFiles() from server side i should be able to access files attached to each request.

Raju
  • 459
  • 5
  • 23
gihan-maduranga
  • 4,381
  • 5
  • 41
  • 74
  • can I post answer for node.js backend? I have used ng-file-upload module to upload multiple images along with other form data in one go. – Gandalf the White Jan 25 '16 at 11:33
  • @Gandalf the White please post it maybe i can get some idea looking at your code.thanks – gihan-maduranga Jan 25 '16 at 16:21
  • Have you tried `Upload.upload({url:'...', data: {lName: tc.lName, ..., files: $scope.files}})` ? – danial Jan 25 '16 at 16:42
  • @danial yes some how i can send `$scope.files` to my server side.but i dont have much idea about how can i access file array in my server side code.becasue in angularJs i can set only `file type,name,and size` but there is no way to set file content along with those attributes.so my requirment is that get the each file content to a `String variable` so please if you know how can i set file content along with the request and access it in server side let me know . like can i cast `$scope.files` to a file and access attributes in server side or any other way to get file content. – gihan-maduranga Jan 25 '16 at 16:49
  • 2
    Just use the docs on the github, send the files similar to jsfiddle sample, and there is Spring MVC samples in the doc, use the code from there. You dont need to convert it to string on the client side, just use the syntax that are in the example to read the multipart request file content it is a byte array. – danial Jan 25 '16 at 20:28
  • 1
    https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/java/com/df/angularfileupload/FileUpload.java Take a look at this. Your problem isn't on the frontend part and therefore my codes wont be useful for you. – Gandalf the White Jan 26 '16 at 05:57

1 Answers1

4

Multiple File Upload using AngularJS: Server requesting with JSON text and multipart file data.


Client Side Script and its fiddle.

window.onload = function() {
 var app = angular.module("myapp", []);
    app.controller("uploadcontroller", function uploadcontrollerFun($scope, $http) {
      
      $scope.files = [];
      $scope.getFileDetails = function(e) {
        $scope.$apply(function() {
          for (var i = 0; i < e.files.length; i++) {
            var isFileAvailable = false;
            console.log("File Name  " + e.files[i].name);
            for (var j = 0; j < $scope.files.length; j++) {
              if ($scope.files[j].name === e.files[i].name) {
                isFileAvailable = true;
                break;
              }
            }
            if (!isFileAvailable) {
              $scope.files.push(e.files[i]);
            } else {
              alert("file is already available ::" + e.files[i].name)
            }
          }
        });
      }
      
      $scope.submitdata = function() {
        var data = new FormData();
        for (var i in $scope.files) {
          data.append("uploadFile[" + i + "]", $scope.files[i]);
        }
        data.append("key1", 'email');
        console.log("data",data);
        var targetRequestPath =  //'./UploadScenarioFiles'; // Controller URL
           'http://localhost:8080/PerformanceUI/UploadScenarioFiles';
        
        $http({
          method: 'POST',
          url: targetRequestPath,
          headers: {
            'Content-Type': undefined
          },
          data: data
        }).then(function(response) {
          console.log('Response Data : ', response.data);
          callback(response.data);
        })
      }
    });
}
<html>
 <head>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
 </head>
 <body>
  <div class="form-group ng-scope" ng-app="myapp" ng-controller="uploadcontroller">
    <label class="control-label col-sm-3"> Import File 
      <span class="error">*</span>
    </label>
    <div class="col-lg-6 col-sm-6 col-12">
      <label class="btn btn-primary">
        <input type="file" id="f" accept=".txt,.csv,.jmx " multiple="" onchange="angular.element(this).scope().getFileDetails(this);this.value=null;">
      </label>
      <br><br>
      <button class="btn btn-success" ng-click="submitdata()">  submit </button>
    </div>
  </div>
 </body>
</html>

Spring Controller to consume multipart and json text.

@RequestMapping(value = "/UploadScenarioFiles", method = RequestMethod.POST)
public void UploadscenarioFiles(HttpServletRequest request, HttpServletResponse response) {
    String param1;
    if (request != null) { // JSON Text
        param1 = request.getParameter("key1");
    }
    MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
    Iterator<String> fileNames = multipart.getFileNames();
    while (fileNames.hasNext()) { // Get List of files from Multipart Request.

        MultipartFile fileContent = multipart.getFile(fileNames.next());

        // Save files to Local (or) any Storage server.
        File file = new File("E:\\AA\\test\\"+fileContent.getOriginalFilename());
        fileContent.transferTo( file );

    }
}

We can set File size limit in the spring configurationFile link

     <!-- setting maximum upload size -->
    <beans:property name="maxUploadSize" value="100000" />

</beans:bean>
Raju
  • 459
  • 5
  • 23