Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the Image as ResponseEntity<byte[]> and display same using Thyme leaf

I am using thyme leaf for one my project, I have problem in generating a QRCode and display the same in browser and I am using spring mvc framework.

  1. I will send the product id to API layer, that has to create QR code for that id. That should not save in anywhere and return as response as byte[]
  2. using thyme leaf framework have to display the image in browser

Please help on the same.

Regards Mohan

like image 860
Mohankumar D Avatar asked Sep 20 '25 07:09

Mohankumar D


1 Answers

Just send a HTTP request to your controller.

In your Thymeleaf template, set the source of your image to the url of your Spring MVC controller:

<img th:src="@{/controller/qr/${id}}" />

Provide a method in your controller that returns the image as ResponseEntity:

@RequestMapping (value="/qr/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getQRImage(@PathVariable final String id) {
    byte[] bytes = ...; // Generate the image based on the id

    // Set headers
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<byte[]> (bytes, headers, HttpStatus.CREATED);
}

More answers can be found in this question: Spring MVC: How to return image in @ResponseBody?

like image 99
Tom Verelst Avatar answered Sep 22 '25 20:09

Tom Verelst