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,而不是存儲在數據庫或外部服務器/雲中。 –