My problem is simple and complex at the same time:
I am trying to upload files using the jQuery fileUpload library with a spring mvc controller on the server side, but my files are downloaded with a single request. I want to publish ALL of them in ONE request.
I tried the singleFileUploads: false parameter, but it does not work if I pass 4 files to upload, the method responsible for processing the message is called 4 times.
Im using this form to publish files:
<div class="upload-file-div"> <b>Choose csv files to load</b> <input id="csvUpload" type="file" name="files[] "data-url="adminpanel/uploadCsv" multiple /> </div> <div id="dropzoneCsv">Or drop files here</div> <div id="progressCsv"> <div class="bar" style="width: 0%;"></div> </div>
Jquery method to upload files:
$('#csvUpload').fileupload( { singleFileUploads: false, dataType : 'json', done : function(e, data) { $("tr:has(td)").remove(); $.each(data.result, function(index, file) { $("#uploaded-csv").append( $('<tr/>').append( $('<td/>').text(file.fileName)) .append( $('<td/>').text( file.fileSize)) .append( $('<td/>').text( file.fileType)) .append( $('<td/>').text( file.existsOnServer)) .append($('<td/>'))); }); }, progressall : function(e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progressCsv .bar').css('width', progress + '%'); }, dropZone : $('#dropzoneCsv') });
And the handler method:
@RequestMapping(value = "/adminpanel/uploadCsv", method = RequestMethod.POST) public @ResponseBody List<FileMeta> uploadCsv(MultipartHttpServletRequest request, HttpServletResponse response) { // 1. build an iterator Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null; List<FileMeta> csvFiles = new ArrayList<FileMeta>(); // 2. get each file while (itr.hasNext()) { // 2.1 get next MultipartFile mpf = request.getFile(itr.next()); System.out.println(mpf.getOriginalFilename() + " uploaded! "); // 2.3 create new fileMeta FileMeta fileMeta = new FileMeta(); fileMeta.setFileName(mpf.getOriginalFilename()); fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb"); fileMeta.setFileType(mpf.getContentType()); try { File dir = new File(Thread.currentThread().getContextClassLoader() .getResource("").getPath()+"CSV"); if(!dir.exists()) dir.mkdirs(); File newCSV = new File(dir+"\\"+ mpf.getOriginalFilename()); if(!newCSV.exists()) { mpf.transferTo(newCSV); fileMeta.setExistsOnServer(false); } else fileMeta.setExistsOnServer(true); } catch (IllegalStateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // 2.4 add to files csvFiles.add(fileMeta); } return csvFiles; }
I really need help here :( Files should be loaded in a single request, which is why I am doing an iterator, but it just doesn't work.
ps. Sorry for my scary english :(