如何使用Spring和JSP在列表中显示上载的文档

时间:2018-07-18 05:38:41

标签: javascript spring jsp

@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.";
    }
}

我已将文档上载到服务器文件夹,并且要显示所有已上传的文档。

1 个答案:

答案 0 :(得分: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());
      }
    }