Search code examples
javascriptjavaserverside-javascriptmultiple-file-upload

AJAX controller not looping through each file and saving in location. Only doing the first file upload


My below code is only uploading the first file in an array to the path location. Can anyone see what is wrong with my server side controller:

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);
        logger.info(directory.toString());
                if (! directory.exists()){
                    directory.mkdir();
                    logger.info("directory created");
                  }
            byte[] bytes = file.getBytes();
            logger.info(bytes.toString());
            Path path = Paths.get(UPLOADED_FOLDER + number + "//" + file.getOriginalFilename());
            logger.info(path.toString());
            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";
}

}

Solution

  • return("File Uploaded");
    

    This breaks out of the loop.

    You need to put return after the loop ends if you want it to run completely.