如何将Image作为ResponseEntity <byte []>返回并使用Thyme leaf显示相同内容

Moh*_*r D 1 java spring-mvc thymeleaf

我正在使用百里香叶作为我的项目,我在生成QRCode时遇到问题,并在浏览器中显示相同的问题,我正在使用spring mvc框架.

  1. 我将产品ID发送到API层,该层必须为该ID创建QR码.这不应该保存在任何地方并作为响应返回byte []
  2. 使用百里香叶框架必须在浏览器中显示图像

请帮忙.

关心莫汉

Tom*_*lst 5

只需向控制器发送HTTP请求即可.

在Thymeleaf模板中,将图像源设置为Spring MVC控制器的url:

<img th:src="@{/controller/qr/${id}}" />
Run Code Online (Sandbox Code Playgroud)

在控制器中提供一个返回图像的方法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);
}
Run Code Online (Sandbox Code Playgroud)

在这个问题中可以找到更多答案:Spring MVC:如何在@ResponseBody中返回图像?