我创建了一个弹簧网络应用程序,用于将图像存储为blob并显示<img>
标记。如何在页面上显示?它没有在我的页面上使用百万富翁模板引擎显示image.img。
我试过这段代码:
<img th:attr="src=@{${Advertising.image}} , title=#{background}, alt=#{background}"
width="20" height="20"/>
@RequestMapping("/ViewAd.html")
public String viewAdvertise(ModelMap map) throws IOException {
map.addAttribute("Advertising", advertisingDAO.findById(2));
return "/admin/EditAdvertisement";
}
答案 0 :(得分:7)
作为Nizet答案的扩展,这里有一些代码可以举例说明:
@EnableAutoConfiguration
@ComponentScan
@Controller
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@RequestMapping(value = "/home")
public ModelAndView home() throws IOException {
ModelAndView view = new ModelAndView("index");
view.addObject("image_id", 1);
return view;
}
@RequestMapping(value = "/image/{image_id}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<byte[]> getImage(@PathVariable("image_id") Long imageId) throws IOException {
byte[] imageContent = //get image from DAO based on id
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(imageContent, headers, HttpStatus.OK);
}
}
<强>的index.html 强>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>
You can find <b>your inlined image</b> just below this text.
</p>
<p>
<img th:src="@{/image/${image_id}}" />
</p>
<p>
Regards, <br />
<em>The Thymeleaf Team</em>
</p>
</body>
</html>
答案 1 :(得分:1)
HTML img标记的src属性不包含图像的字节。它包含图像的URL。然后,浏览器向此URL发出请求,并获取图像的字节作为响应(以及Content-Type响应头中的mime类型)。
因此,您需要一个Spring控制器,它将广告的ID作为参数(或路径参数),将加载图像字节,并将它们发送到响应。您需要将此控制器的URL放在src
属性中:
我不知道百万美元的语法,但生成的HTML应该看起来像
<img src="/myApp/AdvertisingImages/1234" />
或
<img src="/myApp/AdvertisingImages?advertisingId=1234" />