问题描述
我正在使用带有 thymeleaf 的 spring mvc 将图像上传到服务器并在单独的页面“结果”中提交表单后显示它。
问题是图像不会显示,直到我刷新 Spring Tool Suite 中的资源文件夹“resources/static/images”然后刷新页面。 我修改了eclipse工作区选项以自动刷新,ide部分解决了,但仍然需要刷新结果页面才能显示图像
这是控制器代码
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String contentSubmit(@Valid @ModelAttribute ContentEntity cm, BindingResult result,
@RequestParam("file") MultipartFile file, Model model) {
if (!file.isEmpty()) {
try {
cm.setImgUrl(file.getOriginalFilename());
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("src/main/resources/static/images/"+cm.getImgUrl())));
stream.write(bytes);
stream.close();
} catch (Exception e) {
//return error page
}
}
if (result.hasErrors()) {
return "cms";
}
contentDao.addContent(cm);
return "view";
}
这是视图代码
<img th:src="@{'images/'+${contentEntity.imgUrl}}" class="image-responsive thumbnail" />
1楼
您正在“src/resources/...”目录中创建一个资源(图像文件)。 但是,您的服务器似乎是来自不同目录(例如 target/** 或 bin/**)的 serverig 图像。 因此,当您刷新资源目录时,STS 确实会检测到最近创建的新文件,然后将文件复制到目标目录下。
Eclipse 中有一个“本地钩子或轮询”选项,它不断监视资源的变化(即使是在 STS/eclipse 外部进行的)。 一旦检测到更改,资源将自动刷新。
您可能希望通过以下方式设置此选项:首选项 > 常规 > 工作区 > “使用本机钩子或轮询刷新”
希望这可以帮助。
2楼
我解决的另一种方法是,除了将图像仅存储在资源/静态/图像中,您还可以将它们保存在目标/类/静态/图像中,服务器将能够在不刷新的情况下查看新添加的图像。