0

I have an ajax request which is working as I am able to see the number of files, the file names and the looping. I am trying to get these saved to a local folder on my computer. I have an @RequestParam for two variables, a number (string) and files (an array). It seems to work for one file, but does not save the next file. Can anyone figure out why ?

    function makeProgress(number){   
      var url = getRelativeURL("web/fileUpload");        
      var formData = new FormData();
      formData.append('number', number);
      fls = document.getElementById("attachmentFileUploadInput").files; //number of files... 
      console.log(fls);
      for(j=0;j<fls.length;j++){
          formData.append('files[]', fls[j]);  //note files[] not files
          $.ajax({
              url : url,
              data : formData,
              processData : false,
              contentType: false,
              type : 'POST',
              success : function(data) {
               FileUploadVisible(true);
               $('#attachmentModal').modal('hide')
               $(':input','#attachmentModal').val("");
                $("#pbarmain").hide();
                $("#pbar").hide();
                $("#actionPlanDiv").hide();
                setObjectEnabled('#Upload',false);
              },
              error : function(err) {
                  FileUploadErrorVisible(true);
              }
         });
          console.log('loop each file working');
      }
      console.log("form data " + formData);


        }

Server side - this is where something is going wrong, only saving the first file in a folder:

private static String UPLOADED_FOLDER = "C://temp//";

@RequestMapping(value = { "/fileUpload" }, method = RequestMethod.POST)
@ResponseBody
public String uploadFile( @RequestParam("number") String number, @RequestParam("files[]") MultipartFile[] files, MultipartHttpServletRequest req, HttpServletResponse res)
{       

    for (MultipartFile file : files) {
    try {
        File directory = new File(UPLOADED_FOLDER + number);
                if (! directory.exists()){
                    directory.mkdir();
                  }
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + number + "//" + file.getOriginalFilename());
            Files.write(path, bytes);
            logger.info("You have successfully uploaded '" + file.getOriginalFilename() + "'");
            return("File Uploaded");


    } catch (Exception e) {
        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        logger.error("Failed to upload file '" + file.getOriginalFilename() + "'", e);
        return("File Not Uploaded");
    }
}
    return "redirect:/fileUpload";
}

}
RA19
  • 709
  • 7
  • 28
  • Are you getting any errors? – Dave Ranjan Apr 13 '17 at 19:51
  • I am not getting any errors at all. Just doesnt save the second file in the array. If i upload 5 files, it still only saves the first file. – RA19 Apr 13 '17 at 19:53
  • Are you gettting `logger.info("You have successfully uploaded '" + file.getOriginalFilename() + "'"); ` this log 5 times? – Dave Ranjan Apr 13 '17 at 19:54
  • In the console, I am getting looping printed twice, so i know the ajax request is going through twice. I dont think its parsing into the array to the server side. If that makes sense? – RA19 Apr 13 '17 at 19:55
  • Line 130463: 2017-04-13 20:52:24.566 INFO c.g.o.i.controller.AjaxController.401 - You have successfully uploaded 'test.txt' I only get it once – RA19 Apr 13 '17 at 19:56
  • 1
    I think your file is getting overridden. So, its writing content to same file every time. – Dave Ranjan Apr 13 '17 at 19:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/141674/discussion-between-ra19-and-dave-ranjan). – RA19 Apr 13 '17 at 19:57
  • Line 130665: 2017-04-13 21:06:01.974 INFO c.g.o.i.controller.AjaxController.401 - You have successfully uploaded 'test.txt' Line 130672: 2017-04-13 21:06:01.979 INFO c.g.o.i.controller.AjaxController.401 - You have successfully uploaded 'test.txt' You are correct, it printed this twice with the same file name at the same time. How do i get this to stop? – RA19 Apr 13 '17 at 20:07
  • Line 131251: 2017-04-13 21:08:37.882 INFO c.g.o.i.controller.AjaxController.401 - You have successfully uploaded 'A.txt' Line 131293: 2017-04-13 21:08:37.900 INFO c.g.o.i.controller.AjaxController.401 - You have successfully uploaded 'A.txt' Line 131353: 2017-04-13 21:08:37.930 INFO c.g.o.i.controller.AjaxController.401 - You have successfully uploaded 'A.txt' – RA19 Apr 13 '17 at 20:09
  • Sorry I was away. So you got the problem? – Dave Ranjan Apr 13 '17 at 20:50
  • I understand the problem, unsure on how to resolve it still. Im guessing its related to this, but not 100% for (MultipartFile file : files) { } – RA19 Apr 13 '17 at 21:00
  • Do you know how to fix this? – RA19 Apr 13 '17 at 21:31
  • Still cant get it working – RA19 Apr 13 '17 at 21:58
  • Hey can you confirm one last thing. can you add `async : false` to your ajax request. I think your ajax request is skipping. – Dave Ranjan Apr 13 '17 at 22:48
  • I added async : false to the ajax request, that still did not work. It still only saved A.txt once. Any other ideas? – RA19 Apr 14 '17 at 06:01
  • Do you think the issue is related to the original file name part, maybe it's not setting the next one In the array when it loops? – RA19 Apr 14 '17 at 06:14
  • Cant resolve this, anyone able to help? – RA19 Apr 14 '17 at 18:32

1 Answers1

1

return("File Uploaded"); This breaks out of the loop. Needed to put return after the loop ends if you want it to run completely.

RA19
  • 709
  • 7
  • 28