Reputation: 1237
I have a Spring Boot REST server.
The controller is returning the stored image as :
@ResponseBody ResponseEntity<Resource> myController(@PathVariable("id") final Long id){
...
}
How do I display it in my html page ?
<html>
...
<img src="???"/>
...
</html>
I can add a JQUERY / AJAX code that will retrieve the picture for me this way, but what do i do with it then ?
Upvotes: 0
Views: 2650
Reputation: 1237
I finally found the solution in these links :
https://o7planning.org/en/11765/spring-boot-file-download-example https://community.liferay.com/forums/-/message_boards/message/26404099
1) I read the image as a byte array
2) I must encode it to Base64
I use Base64.getEncoder().encodeToString(my-image-bytes).getBytes()
3) I return it as ByteArrayResource :
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + name + "\"")
.contentLength(data.length)
.body(new ByteArrayResource(data));
4) in my page, i load it as an image this way :
$.ajax({
url: 'url-to-get-image-api-controller',
type: 'GET',
statusCode:{
200: function(data){
$("#thumb1").html('<img src="data:image/jpg;base64,' + data + '" />');
}
}
});
This works.
Upvotes: 2