Java 如何将图像返回为 ResponseEntity<byte[]> 并使用百里香叶显示相同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21331546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return the Image as ResponseEntity<byte[]> and display same using Thyme leaf
提问by Mohankumar D
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.
我在我的一个项目中使用百里香叶,我在生成 QRCode 并在浏览器中显示它时遇到问题,我正在使用 spring mvc 框架。
- 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[]
- using thyme leaf framework have to display the image in browser
- 我会将产品 id 发送到 API 层,该层必须为该 id 创建 QR 码。那不应该保存在任何地方并作为响应返回 byte[]
- 使用百里香叶框架必须在浏览器中显示图像
Please help on the same.
请帮忙。
Regards Mohan
问候莫汉
采纳答案by Tom Verelst
Just send a HTTP request to your controller.
只需向您的控制器发送 HTTP 请求即可。
In your Thymeleaf template, set the source of your image to the url of your Spring MVC controller:
在您的 Thymeleaf 模板中,将图像源设置为 Spring MVC 控制器的 url:
<img th:src="@{/controller/qr/${id}}" />
Provide a method in your controller that returns the image as ResponseEntity
:
在控制器中提供一个方法,将图像返回为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?
更多答案可以在这个问题中找到:Spring MVC: How to return image in @ResponseBody?