我正在尝试将文件上传到服务器上,但是每次启动应用程序时,它都会在服务器中创建一个文件夹,然后在该文件夹中上传文件。如何存储永久上传的文件,以便每当我启动应用程序时,它就会使用现有文件以获得更多功能,或询问用户服务器上是否不存在该功能。
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String index(Model model, @RequestParam("file") MultipartFile[] files,RedirectAttributes rm) {
List<String> ls = new ArrayList<>();
try {
for (int i = 0; i < files.length; i++) {
if (!files[i].isEmpty()) {
System.out.println("sdfghjk");
ls.add(files[i].getOriginalFilename());
byte[] bytes = files[i].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 + files[i].getOriginalFilename());
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
logger.info("Server File Location=" + serverFile.getAbsolutePath());
} else {
rm.addFlashAttribute("error","all the fies are needded");
return "redirect:/uploadForm";
}
}
model.addAttribute("list", ls);
model.addAttribute("message", "succsesfully uploaded");
return "NewFile";
} catch (Exception e) {
model.addAttribute("message", "failed to upload");
System.out.println("catch");
return "NewFile";
}
}