Angularjs and spring mvc - download multiple files with one request

I want to implement file upload in my web application, I use angular.js on the client side and spring mvc on the server side.

I was able to upload a single file and upload multiple files using https://github.com/danialfarid/angular-file-upload . The fact is that when I upload several files, each of them comes to me as a separate request (which is an obvious event after the reading example code):

 //inject angular file upload directives and service. angular.module('myApp', ['angularFileUpload']); var MyCtrl = [ '$scope', '$upload', function($scope, $upload) { $scope.onFileSelect = function($files) { //$files: an array of files selected, each file has name, size, and type. for (var i = 0; i < $files.length; i++) { var $file = $files[i]; $scope.upload = $upload.upload({ url: 'server/upload/url', //upload.PHP , node.js route, or servlet url // method: POST or PUT, // headers: {'headerKey': 'headerValue'}, withCredential: true, data: {myObj: $scope.myModelObj}, file: $file, //(optional) set 'Content-Desposition' formData name for file //fileFormDataName: myFile, progress: function(evt) { console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total)); } }).success(function(data, status, headers, config) { // file is uploaded successfully console.log(data); }) //.error(...).then(...); } } }]; 

there is an iteration over all files.

Now I am wondering if it is possible to somehow upload multiple files as one, one request.

+6
source share
1 answer

on the spring side of the controller create

 @RequestMapping(value = "/upload", method = RequestMethod.POST) public String save(@ModelAttribute("filesForm") FileUploadForm filesForm) { List<MultipartFile> files = filesForm.getFiles(); //do something } public class FileUploadForm { private List<MultipartFile> files; // geters and setters ... } 

on the client side download service

 return { send: function(files) { var data = new FormData(), xhr = new XMLHttpRequest(); xhr.onloadstart = function() { console.log('Factory: upload started: ', file.name); $rootScope.$emit('upload:loadstart', xhr); }; xhr.onerror = function(e) { $rootScope.$emit('upload:error', e); }; xhr.onreadystatechange = function(e) { if (xhr.readyState === 4 && xhr.status === 201) { $rootScope.$emit('upload:succes',e, xhr, file.name ,file.type); } }; angular.forEach(files, function(f) { data.append('files', f, f.name); }); xhr.open('POST', '../upload'); xhr.send(data); } }; 
+1
source

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


All Articles