3

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

Mohankumar D
  • 63
  • 1
  • 2
  • 8

1 Answers1

8

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?

Community
  • 1
  • 1
Tom Verelst
  • 15,324
  • 2
  • 30
  • 40
  • Retrieve the byte[] content and convert it into `Base64.getEncoder().encodeToString(byte[] content)` then set it as a Context Variable and then process the templateEngine to the pass the variable as `` in Thymeleaf – KNDheeraj Sep 21 '18 at 09:51