我正在使用Spring MVC和Thymeleaf上传图像到服务器,并在提交表单后在一个名为“result”的单独页面中显示它。
问题是,图像在我刷新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" />
src/main/resources/
目录中提供图像。它们是通过从该目录(以及其他目录)构建的 Web 应用程序提供的。将 Web 应用程序视为一个大的 war 文件,你无法在运行时修改它(因为这就是它应该的样子)。将上传的图像视为数据,在生产 Web 服务器上存储在 应用程序之外 或数据库中,因为它们就是这样。你需要一个 Servlet 或 Controller 来获取图像 ID,读取相应的文件或数据库 blob,并使用适当的内容类型将数据发送回浏览器。 - JB Nizet