2
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        String name=file.getOriginalFilename();
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator +name );
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            return "You successfully uploaded file=" + name;
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload  because the file was empty.";
    }
}

I have uploaded document to server folder,and I want to show all the documents that I have uploaded.

flyingfox
  • 13,414
  • 3
  • 24
  • 39
DJavaD
  • 39
  • 3
  • 2
    Have you tried it yourself? If so, can you show us some code of how you tried to do this? – ech0 Jul 18 '18 at 05:40
  • I have shared the code that I have used. – DJavaD Jul 18 '18 at 05:50
  • This code doesn't show any attempt to actually list the files, it's your upload code. – ech0 Jul 18 '18 at 05:52
  • yes,But I want to know how can I do that,and when I will choose any of the document ,it should be shown in jsp iframe. – DJavaD Jul 18 '18 at 05:57
  • So you haven't even tried to research this issue yourself, you simply decided to ask for the answer right away? – ech0 Jul 18 '18 at 06:01

1 Answers1

1
File folder = new File("path/to/your/uploaded/files/directory");
File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
      } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory " + listOfFiles[i].getName());
      }
    }
Jagadesh jakes
  • 107
  • 1
  • 10
  • It is showing on console ,but if I want to display in a web page?Thank you. – DJavaD Jul 18 '18 at 08:16
  • Use ajax to call the servlet and write the list of files as json object in the response and get it on ajax success. Refer these links you will get an idea https://www.journaldev.com/4742/jquery-ajax-jsp-servlet-java-example and https://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax – Jagadesh jakes Jul 18 '18 at 12:01