Reputation: 177
I created a spring web app for storing image as a blob and showing with an <img>
tag. How can I show it on a page? It does not show image.img using thymeleaf template engine on my page.
I tried this code:
<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";
}
Upvotes: 3
Views: 10310
Reputation: 2803
As an extension to Nizet's answer, here is some code to exemplify:
@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>
Upvotes: 9
Reputation: 691635
The src attribute of the HTML img tag doesn't contain the bytes of an image. It contains the URL of an image. The browser then makes a request to this URL, and gets the bytes of the image as a response (along with its mime type in the Content-Type response header).
So you need to have a Spring controller which will taje the ID of an Advertising as parameter (or path parameter), will load the image bytes, and send them to the response. And you need to put the URL of this controller in the src
attribute:
I don't know the thymeleaf syntax for that, but the generated HTML should look like
<img src="/myApp/AdvertisingImages/1234" />
or
<img src="/myApp/AdvertisingImages?advertisingId=1234" />
Upvotes: 1