Issue
I have a question... I can to display titles of all posts that received from database via Iterable<PostModel> postsMain = postRepository.findAll();
(it also contains blob-images). But I can't understand correctly: For displaying of single image I getting byte code from DB and encoding it in base64 code, How do this with multiple images and display them like titles?
I displaying single image like this:
Optional<PostModel> post = postRepository.findById(id);
byte[] encodeBase64 = Base64.encodeBase64(post.get().getImage());
String base64Encoded = new String(encodeBase64, "UTF-8");
modelAndView.addObject("contentImage", base64Encoded );
HTML-source: <img class="post-image" th:src="@{'data:image/jpeg;base64,'+${contentImage}}">
I tryed to create List
where I adding an base64 encoded string values.
My controller:
@GetMapping("/")
public ModelAndView home ( Model model) throws UnsupportedEncodingException {
ModelAndView modelAndView = new ModelAndView("home");
Iterable<PostModel> postsMain = postRepository.findAll();
List<String> contentImages = new ArrayList<>();
int size = Iterables.size(postsMain);
for(int count = 0; count <= size; count++) {
byte[] encodeBase64 = Base64.encodeBase64(postsMain.iterator().next().getImage());
String base64Encoded = new String(encodeBase64, "UTF-8");
contentImages.add(base64Encoded);
}
modelAndView.addObject("contentImages", contentImages);
modelAndView.addObject("posts_main", postsMain);
return modelAndView;
}
Good wishes.
Solution
This problem was solved.
@GetMapping("/")
public ModelAndView home ( Model model) throws UnsupportedEncodingException {
ModelAndView modelAndView = new ModelAndView("home");
List<PostModel> postsMain = (List<PostModel>) postRepository.findAll();
int size = Iterables.size(postsMain); //Receiving size of Iterator
byte[] encodeBase64 = new byte[size];
for(int count = 0; count < size; count++) {
encodeBase64 = Base64.encodeBase64(postsMain.get(count).getImage());
String base64Encoded = base64Encoded = new String(encodeBase64, "UTF-8");
postsMain.get(count).setMainPageImage(base64Encoded);
}
modelAndView.addObject("posts_main", postsMain);
return modelAndView;
}
UPDATED: I added another, similar field in my PostModel
(That also have getters ans setters) This field will not uploaded to DB:
private String mainPageImage;
Then I setting received Base64
code via setter in for
loop (above) like this:
postsMain.get(count).setMainPageImage(base64Encoded);
And finally, We're got this HTML
section where displaying the picture and title from single collection:
<main>
<div class="post-section">
<div class="main-post" th:each="post : ${posts_main}">
<div class="container">
<img class="post-image" th:src="@{'data:image/jpeg;base64,'+${post.mainPageImage}}"/>
<a href="/"><span th:text="${post.title}"></span></a>
</div>
</div>
</div>
</main>
Answered By - Igor Gorski