java 如何在thymeleaf中将图像从数据库插入页面

svgewumm  于 2023-02-21  发布在  Java
关注(0)|答案(1)|浏览(139)

我不明白如何发送到浏览器我的图像从服务器。我的代码如下。为什么它不工作?当我从数据库获取字节并将其保存到磁盘图像打开罚款。在html中有下一个代码:

<div th:fragment="image_list">
    image will be here
    <p>
        <img class="picture" th:src="@{/image/1}"/>
</div>

Java控制器类:

@GetMapping(value = "/{id}")
    @ResponseBody
    public ResponseEntity<InputStreamResource> getCarImage(@PathVariable Long id) {
        var image = imageService.getOne(id);
            
        var imageDecompressed = decompressBytes(image.getImage());
        InputStream inputStream = new ByteArrayInputStream(imageDecompressed);
        return ResponseEntity.ok()
                .contentLength(image.getImage().length)
                .contentType(MediaType.IMAGE_JPEG)
                .body(new InputStreamResource(inputStream));
    }


    public static byte[] decompressBytes(byte[] data) {
        Inflater inflater = new Inflater();
        inflater.setInput(data);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        try {
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            }
            outputStream.close();
        } catch (IOException ioe) {
        } catch (DataFormatException e) {
        }
        return outputStream.toByteArray();
    }

euoag5mw

euoag5mw1#

使用此示例

@ResponseBody
@GetMapping(value = "/{id}")
public byte[] getImageAsByteArray(@PathVariable int id) {
     return imageService.getOne(id).getImage();
}

相关问题