0
我正在为我的Spring MVC项目开发一个图像管理系统,其基本功能是显示存储在本地图像文件夹中的所有图像库,删除图像和上传新图像。Spring MVC Resources not refreshing
我想,一旦上传新图片,页面会重新加载图片库,包括刚添加的图片。它发生在事实是,新的图像正确保存在HD,但它不会自动在Java项目的资源/ IMG文件夹显示;因此,一旦页面被重新加载,新的图像就不存在了。只有当我手动刷新项目时,新图像才会显示在resources/img文件夹中。
奇怪的是,我没有与删除方法相同的问题:一旦图像被删除,它将从HD和resources/img文件夹中消失,并且页面将重新加载图库而不显示图像刚删除。
任何想法,问题可能是什么?
这里是我的控制器
@Controller
public class imagesManagerController {
// READ ALL FILES FROM IMG FOLDER
@RequestMapping(value = "/imagesManager", method = RequestMethod.GET)
public ModelAndView readImages
(@RequestParam(value = "error", required = false) String error) {
// create model and link it to jsp imagesManager
ModelAndView model = new ModelAndView("imagesManager");
// return content from images folder and add it to model
File imgsPath = new File("C:/Users/Alessandro/workspace/SpringMVCBlog/WebContent/resources/img");
String[] imgsNames = imgsPath.list();
model.addObject("imgsNames", imgsNames);
//if upload fails, display error message
if (error != null) {
model.addObject("error",
"Please select a file to upload");
}
return model;
}
//UPLOAD FILE TO HD
@RequestMapping(value = "/imagesManager/upload", method = RequestMethod.POST)
public String handleFileUpload (@RequestParam("file") MultipartFile file) {
//get img name
String imgName = file.getOriginalFilename();
System.out.println(imgName);
//create file path
String folder = "C:/Users/Alessandro/workspace/SpringMVCBlog/WebContent/resources/img/";
File path = new File (folder+imgName);
System.out.println(path);
if (!file.isEmpty()) {
try {
//get bytes array from file
byte[] bytes = file.getBytes();
//create output stream
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(path));
//write img content on path
stream.write(bytes);
//close stream
stream.close();
//if upload is successful, reload page
return "redirect:/imagesManager";
} catch (Exception e) {
return "You failed to upload " + imgName + " => " + e.getMessage();
}
} else {
return "redirect:/imagesManager?error";
}
}
// DELETE FILE FROM HD
@RequestMapping(value = "/imagesManager/delete", method = RequestMethod.POST)
public String deleteFile(@RequestParam (value="imgName") String imgName) {
//create file path to be deleted
String folder = "C:/Users/Alessandro/workspace/SpringMVCBlog/WebContent/resources/img/";
File path = new File (folder+imgName);
// delete file
if (path.delete()) {
//if delete is successful, reload page
return "redirect:/imagesManager";
} else {
return "Delete operation failed";
}
}
}
我要上传的文件保存在本地磁盘上。所以你的意思是我不应该将它们保存在IDE项目文件夹中,而是保存在其他地方(例如C:\ Users \ Public \ Pictures)? –
正确。对于生产部署,您应该使用云或专用文件服务器。 –
好的,但如果我不保存在IDE项目文件夹中的文件,我怎样才能在控制器中读取它们?请考虑我希望将文件以本地磁盘存储为jpg,而不是存储在数据库或外部服务器/云中。 –